diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html index 7e2ad3e..14f4544 100644 --- a/app/modules/notice/templates/notice/admin.html +++ b/app/modules/notice/templates/notice/admin.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index a0e7d64..9b3bbe0 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -33,6 +33,12 @@ - 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003). - 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). +## 매출 실적 화면 (2026-10-19) + +- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음. +- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. +- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김). + ## 광고비 (`/performance/ads`) - 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 7abbed6..d736cf6 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -6,7 +6,7 @@ HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권 from __future__ import annotations from datetime import date, timedelta -from decimal import Decimal +from decimal import ROUND_HALF_UP, Decimal from typing import Any, Mapping, Sequence from . import calc @@ -32,6 +32,90 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] return (status_row or {}).get("status") or "unknown" +# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름) +UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")} +UNIT_COOKIE = "perf_unit" + + +def normalize_unit(value: Any) -> str: + return value if value in UNITS else "won" + + +def amount_text(value: Any, unit: str = "won") -> str: + """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림).""" + div, places, _ = UNITS[normalize_unit(unit)] + if div == 1: + return f"{int(value):,}" + q = (Decimal(int(value)) / div).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP) + return f"{q:,.{places}f}" + + +def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any], + period: Any, q_start: date, q_end: date) -> None: + """매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS). + 카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). + 광고비 표(005)가 없거나 읽기 실패면 줄 없음.""" + from . import ad_spend # noqa: WPS433 + + by_code = sales_ad_channels() + want = {ch for c in codes for ch, _ in by_code.get(c, ())} + for r in table: + r["ads"], r["ads_total"] = {}, None + if not want: + return + try: + amounts, _ = store.ad_amounts(q_start, q_end) + reader = getattr(store, "ad_roas", None) + roas_map = reader(q_start, q_end) if reader else {} + except Exception: # noqa: BLE001 — 광고비 표가 없어도 매출 화면은 그대로 + return + spend_by: dict[str, list[tuple[date, int]]] = {} + for (d, ch), v in amounts.items(): + if ch in want and v: + spend_by.setdefault(ch, []).append((d, int(v))) + + sales_by: dict[str, list[tuple[date, int]]] = {} + for (d, c), m in cells.items(): + sales_by.setdefault(c, []).append((d, int(m.gross))) + + def spend(ch: str, s: date, e: date) -> int: + return sum(v for d, v in spend_by.get(ch, ()) if s <= d <= e) + + def sales(c: str, s: date, e: date) -> int: + return sum(v for d, v in sales_by.get(c, ()) if s <= d <= e) + + for r in table: + s = date.fromisoformat(r["from"]) if r.get("from") else period.start + e = date.fromisoformat(r["to"]) if r.get("to") else period.end + tot_spend = tot_sales = 0 + for c in codes: + lines = [] + for ch, label in by_code.get(c, ()): + amt = spend(ch, s, e) + if not amt: + continue + rs = ad_spend.channel_roas(ch, lambda m: sales(m, s, e), amt, + lambda f: ad_spend.file_roas(f, roas_map, amounts, s, e)) + lines.append({"label": label, "amount": amt, "roas": rs}) + tot_spend += amt + if lines: + r["ads"][c] = lines + tot_sales += sales(c, s, e) + if tot_spend: + r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, tot_spend)} + + +def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]: + """쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고, + 나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출).""" + from . import ad_spend # noqa: WPS433 + + out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)} + for ch, c in ad_spend.ROAS_SALES_CODE.items(): + out[c] = out.get(c, ()) + ((ch, ""),) + return out + + def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None, custom_to: date | None = None, selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None, @@ -105,6 +189,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "error": (statuses.get(m["code"]) or {}).get("last_error", "")}) m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes) + table = calc.main_table(period, codes, cells, today=today, holidays=holidays) + _ad_lines(store, table, codes, cells, period, q_start, q_end) def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str: if kind == "custom": @@ -144,7 +230,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "short_names": short, "selected_all": len(codes) == len(all_codes), "kpis": kpis, - "table": calc.main_table(period, codes, cells, today=today, holidays=holidays), + "table": table, "month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells), "year": calc.year_months(year_period.start.year, codes, cells, today=today), "chart_daily": calc.daily_series(period, codes, cells), diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 9b617de..0f379b9 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -135,9 +135,20 @@ def dashboard_page( holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())), ) ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross" + _unit_ctx(request, ctx) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) +def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None: + """매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다.""" + from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433 + + unit = normalize_unit(request.cookies.get(UNIT_COOKIE)) + ctx["unit"] = unit + ctx["unit_label"] = UNITS[unit][2] + ctx["amt"] = lambda v: amount_text(v, unit) + + @router.get("/ads", response_class=HTMLResponse) def ads_page( request: Request, @@ -192,6 +203,7 @@ def settings_page(request: Request): ) ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured()) ctx["ad_api_ready"] = store.ad_api_ready() + _unit_ctx(request, ctx) return render_template(request, "performance/settings.html", {**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx}) diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index ac7085b..e2ac119 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 -%} @@ -224,4 +224,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 8d081d7..c3959ac 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,11 +1,19 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} {%- elif v == 0 -%}– - {%- else -%}{{ "{:,}".format(v) }}{%- endif -%} + {%- else -%}{{ amt(v) }}{%- endif -%} +{%- endmacro -%} +{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#} +{%- macro money(v) -%} + {%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}{{ unit_label }}{%- endif -%} +{%- endmacro -%} +{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#} +{%- macro adl(lines) -%} + {%- for a in lines or [] -%}{% if a.label %}{{ a.label }}{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}({{ "{:,}".format(a.roas) }}%){% endif %}{%- endfor -%} {%- endmacro -%} {#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#} @@ -89,7 +97,7 @@ {% for k in kpis %}
{{ k.label }}
-
₩{{ "{:,}".format(k.value) }}
+
{{ money(k.value) }}
{% if k.delta is none %}{{ k.cmp }} 비교 없음 {% else %} @@ -107,6 +115,8 @@

{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}

+ {% if unit != 'won' %}단위: {{ unit_label }}{% endif %} + 광고비(ROAS%) {% if manual_upload_names %} @@ -138,13 +148,13 @@ {% set is_manual = (r.date ~ '|' ~ c) in manual_cells %} {{ m3(m) }} + title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }} {% else %} {{ m3(m) }} + {% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }} {% endif %} {% endfor %} - {{ m3(r.total) }} + {{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %} {% endfor %} @@ -173,7 +183,7 @@
-

{{ month.label }} 쇼핑몰별 누적 실적

+

{{ month.label }} 쇼핑몰별 누적 실적

{% if unit != 'won' %}단위: {{ unit_label }}{% endif %}
@@ -204,11 +214,11 @@
-

{{ year.year }}년 누적

+

{{ year.year }}년 누적

{% if unit != 'won' %}단위: {{ unit_label }}{% endif %}
-
총매출₩{{ "{:,}".format(year.total.gross) }}
-
수수료₩{{ "{:,}".format(year.total.commission) }}
-
수수료 차감 매출₩{{ "{:,}".format(year.total.net) }}
+
총매출{{ money(year.total.gross) }}
+
수수료{{ money(year.total.commission) }}
+
수수료 차감 매출{{ money(year.total.net) }}
쇼핑몰총매출수수료수수료 차감 매출매출 비중
@@ -251,8 +261,9 @@ "period_start": period.start.isoformat(), "period_end": period.end.isoformat(), "today": today, + "unit": unit, "manual_upload_names": manual_upload_names } | 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 3f612f9..c6f028c 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 -%} @@ -102,6 +102,25 @@

+ {# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #} +
+
+

보기 설정

+ 매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다. +
+
+ 매출 단위 +
+ {% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %} + + {% endfor %} +
+ 예: 2,475,300원 → + {% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %} +
+
+ {% if is_admin %} {# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장. 가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #} @@ -183,55 +202,6 @@ -
-

쇼핑몰 원본 데이터 확인

-

쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). - 쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다. - 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
- · 네이버: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.
- · 11번가: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).
- · GS샵: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.
- · 토스쇼핑: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.
- · 쿠팡(윙): 판매자배송 발주서 + 로켓그로스 주문을 결제일로 모아 날짜별 매출 후보(할인 전·후, 취소분 뺀 값, 로켓그로스 따로)와 판매량 — WING 비즈니스 인사이트 → 판매분석에서 같은 날짜의 "매출(원)"·"판매량"과 비교해 주세요.

-
- - - ~ - - -
-
-
- -
-

카페24 매출 대조

-

카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서 - 바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.

-
- - -
-
- -

일별 한 번에 비교

-

카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다. - [API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과 - 규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.

- -
- - -
-
-
-

테스트 데이터

현재 {{ "{:,}".format(sample_count) }}건
@@ -249,4 +219,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_dashboard_ads_units.py b/app/modules/performance/tests/test_dashboard_ads_units.py new file mode 100644 index 0000000..70a60de --- /dev/null +++ b/app/modules/performance/tests/test_dashboard_ads_units.py @@ -0,0 +1,130 @@ +"""매출 실적 화면 — 매출 칸 아래 광고비(ROAS%)·매출 단위(원·천원·백만원) (2026-10-19).""" + +from __future__ import annotations + +from datetime import date + +from app.modules.performance import dashboard + +TODAY = date(2026, 10, 7) + + +class _Store: + """build_dashboard 가 읽는 것만 — 카페24·네이버·쿠팡 매출 + 구글·메타·네이버·쿠팡(윙) 광고비.""" + + def __init__(self, ads_missing=False): + self.ads_missing = ads_missing + + def list_marketplaces(self): + return [{"code": c, "name": n, "enabled": True, "include_in_sales": True} + for c, n in (("cafe24", "카페24"), ("naver", "네이버 스마트스토어"), ("coupang", "쿠팡"))] + + def daily_amounts(self, start, end, codes): + rows = {(date(2026, 10, 5), "cafe24"): 2_000_000, (date(2026, 10, 5), "coupang"): 600_000, + (date(2026, 10, 6), "naver"): 1_234_567} + return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes} + + def rate_table(self): + return {} + + def statuses(self): + return {} + + def last_update_at(self): + return None + + def running_codes(self): + return [] + + def ad_amounts(self, start, end): + if self.ads_missing: + raise RuntimeError("perf_ad_spend 없음") + rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "meta"): 50_000, + (date(2026, 10, 5), "coupang_wing"): 200_000, (date(2026, 10, 6), "naver"): 300_000} + rows = {k: v for k, v in rows.items() if start <= k[0] <= end} + return rows, {k: "manual" for k in rows} + + def ad_roas(self, start, end): + rows = {(date(2026, 10, 5), "google"): 412.5, (date(2026, 10, 6), "naver"): 150} + return {k: v for k, v in rows.items() if start <= k[0] <= end} + + +def test_sales_ad_channels_mapping(): + m = dashboard.sales_ad_channels() + assert m["cafe24"] == (("google", "구글"), ("meta", "메타")) + assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),) + assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m + + +def test_ad_lines_under_sales_cells(): + ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY) + day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") + # 카페24 = 구글·메타 두 줄, ROAS 는 광고 보고서 값(구글 412.5 → 413), 메타는 보고서 ROAS 없음 + assert day5["ads"]["cafe24"] == [{"label": "구글", "amount": 100_000, "roas": 413}, + {"label": "메타", "amount": 50_000, "roas": None}] + # 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000 + assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}] + assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음 + # 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합 + assert day5["ads_total"] == {"amount": 350_000, "roas": 743} # 2,600,000 ÷ 350,000 + day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06") + assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}] + week = next(r for r in ctx["table"] if r["kind"] == "week") + assert [a["amount"] for a in week["ads"]["cafe24"]] == [100_000, 50_000] and week["ads_total"]["amount"] == 650_000 + day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-07") + assert day1["ads"] == {} and day1["ads_total"] is None + + +def test_ad_lines_follow_shop_filter_and_missing_table(): + ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"]) + day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") + assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300} + ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY) + assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로 + + +def test_amount_text_units(): + assert dashboard.amount_text(2_475_300) == "2,475,300" + assert dashboard.amount_text(2_475_300, "thousand") == "2,475" + assert dashboard.amount_text(2_475_500, "thousand") == "2,476" + assert dashboard.amount_text(2_475_300, "million") == "2.5" + assert dashboard.amount_text(158_000, "million") == "0.2" + assert dashboard.amount_text(-158_000, "thousand") == "-158" + assert dashboard.amount_text(1_234_567_890, "million") == "1,234.6" + assert dashboard.amount_text(5, "nope") == "5" and dashboard.normalize_unit("x") == "won" + + +def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch): + 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 _Creds: + def configured_codes(self, adapters): + return {} + + store = _Store() + 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) + + html = client.get("/performance/?period=week&d=2026-10-07").text + assert "2,000,000" in html + assert 'class="perf-adl"' in html and "구글100,000(413%)" in html and "메타50,000" in html + assert "200,000(300%)" in html and "단위:" not in html + + client.cookies.set("perf_unit", "thousand") + html = client.get("/performance/?period=week&d=2026-10-07").text + assert "단위: 천원" in html and "2,000<" in html and "구글100(413%)" in html + assert "2,000,000<" not in html.split("perf-main", 1)[1].split("
", 1)[0] + client.cookies.set("perf_unit", "million") + html = client.get("/performance/?period=week&d=2026-10-07").text + assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html diff --git a/app/modules/project/CLAUDE.md b/app/modules/project/CLAUDE.md index 9f1154c..35341a8 100644 --- a/app/modules/project/CLAUDE.md +++ b/app/modules/project/CLAUDE.md @@ -46,6 +46,7 @@ - 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. - 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표. - 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. +- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(기본 정렬·필터 없음일 때만, 전체 보기는 섹션 맨 끝). 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부). - 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). - 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19). - 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20). @@ -121,3 +122,5 @@ - "주요 업무" 칸 우클릭 위/아래 줄 추가 = 항목 칸은 그대로 그 항목 안에(마이그레이션 027 `label_cont`, 항목 칸 나누기). - 회의록 줄 작업은 새로고침 없이 제자리 다시 그리기(`refreshMeeting`) + 애니메이션. - 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`move-section`). +- 항목 칸 끌어 옮기기(2026-10-19) — 마우스로 항목 칸을 5px 이상 끌면 묶음(label_cont 줄 + 걸친 세로 병합)이 같은 구역 안에서 실시간 이동(칸 단위 FLIP, 구분 칸은 늘 첫 줄), 놓으면 `POST meeting-items/{id}/move-to {before_item_id|null}`(`db.move_meeting_group`, 묶음 사이·다른 구역은 거절) → `refreshMeeting`. Esc 취소, 짧게 누르기는 이름 수정. +- 회의록 표(`.pj-meet-table`) 테두리는 모두 검정 `#000`(2026-10-19, 바깥 아래선은 마지막 줄 칸 아래선이 대신). diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 079e5c9..3ad20a4 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -3549,6 +3549,47 @@ class ProjectStore: for n, x in enumerate(ids): conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) + def move_meeting_group(self, *, item_id: int, before_item_id: int | None) -> bool: + """항목 칸 끌어 옮기기(2026-10-19) — item_id 가 든 묶음(같은 항목 칸으로 이어 붙은 줄 + 걸친 세로 병합)을 통째로 + 같은 구역의 before_item_id 묶음 앞에(None = 구역 맨 끝). 묶음 안 줄 순서·병합은 그대로 따라간다. 바뀌면 True.""" + with self._pool.connection() as conn: + with conn.transaction(): + self._require_meetings(conn) + rows = self._locked_meeting_items(conn, item_id) + ids = [int(r["id"]) for r in rows] + conts = self._meeting_conts(rows) + merges = self._meeting_merge_ranges(rows) + # 묶음 경계 = 이어 붙은 줄이 아니고 병합 범위 안쪽도 아닌 줄(구역이 바뀌는 줄은 늘 경계) + starts = [k for k in range(len(rows)) + if k == 0 or rows[k]["section"] != rows[k - 1]["section"] + or (not conts[k] and not any(a < k <= b for a, b in merges))] + i = ids.index(item_id) + s = max(k for k in starts if k <= i) + e = next((k for k in starts if k > s), len(rows)) + section = rows[s]["section"] + block = ids[s:e] + rest = ids[:s] + ids[e:] + if before_item_id is None: + sec_idx = [n for n, x in enumerate(rest) if rows[ids.index(x)]["section"] == section] + pos = (sec_idx[-1] + 1) if sec_idx else s + else: + if before_item_id not in ids: + raise KeyError(before_item_id) + b = ids.index(before_item_id) + if rows[b]["section"] != section: + raise ValueError("같은 구역 안에서만 옮길 수 있습니다.") + if b not in starts: + raise store.GoalCellConflict("묶인 줄 사이에는 넣을 수 없습니다. 새로고침해 주세요.") + if s <= b < e: + return False + pos = rest.index(before_item_id) + order = rest[:pos] + block + rest[pos:] + if order == ids: + return False + for n, x in enumerate(order): + conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) + return True + def move_meeting_section(self, *, item_id: int, direction: int) -> None: """구역(표 첫 열 "구분") 통째로 한 칸 위/아래 — item_id 가 든 구역 묶음(이어진 같은 구역 줄)과 옆 구역 묶음의 자리를 바꾼다. 묶음 안 줄 순서·세로 병합(content_row_span)은 그대로 따라간다. 맨 위/맨 아래면 그대로.""" diff --git a/app/modules/project/router.py b/app/modules/project/router.py index 51c0ba5..06539f0 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -3981,6 +3981,21 @@ def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any return JSONResponse({"ok": True}) +@router.post("/api/goals/meeting-items/{item_id}/move-to") +def api_move_meeting_group(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """항목 칸 끌어 옮기기 {before_item_id: 그 묶음 앞 | null = 구역 맨 끝} — 묶인 줄·병합은 통째로, 같은 구역 안만. + 줄 순서와 같은 권한(누구나, 회의 완료 전까지).""" + _require_user(request) + st = _db_or_503(request) + before = payload.get("before_item_id") + try: + before = None if before in (None, "") else int(before) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="before_item_id 가 올바르지 않습니다.") + moved = _goal_call(st.move_meeting_group, item_id=item_id, before_item_id=before) + return JSONResponse({"ok": True, "moved": bool(moved)}) + + @router.post("/api/goals/meeting-items/{item_id}/split-label") def api_split_meeting_label(request: Request, item_id: int) -> JSONResponse: """항목 칸 나누기(027) — item_id = 묶음 첫 줄. 이어 붙은 줄들이 각자 항목 칸(이름 빈 칸)으로. 줄 순서와 같은 권한.""" diff --git a/app/modules/project/templates/project/goal_meeting.html b/app/modules/project/templates/project/goal_meeting.html index 664b479..98f92fc 100644 --- a/app/modules/project/templates/project/goal_meeting.html +++ b/app/modules/project/templates/project/goal_meeting.html @@ -1,7 +1,7 @@ {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -298,5 +298,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index c3bc6fd..9ac7aac 100644 --- a/app/modules/project/templates/project/goals.html +++ b/app/modules/project/templates/project/goals.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -207,5 +207,5 @@ {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/help.html b/app/modules/project/templates/project/help.html index 16d9ae8..2b5a2b9 100644 --- a/app/modules/project/templates/project/help.html +++ b/app/modules/project/templates/project/help.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -278,7 +278,8 @@
  • 열기 — 카드를 누르면 오른쪽에 업무 편집 창이 열립니다. (8장)
  • 완료 체크 — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 업무는 녹색 원 안 흰 체크와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 업무는 상태만 표시합니다.
  • 담당자·마감일 바로 바꾸기 — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.
  • -
  • 옮기기 — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.
  • +
  • 옮기기 — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다. + 끄는 동안 카드는 살짝 기울어진 모양으로 마우스를 따라오고, 카드 사이를 지나는 순간 점선 자리가 그 사이로 옮겨 가며 다른 카드가 미끄러지듯 비켜납니다 — 놓으면 그 자리에 그대로 들어갑니다(다른 섹션도 같음). 섹션 밖에 놓으면 원래 자리로 돌아갑니다.
  • 우클릭 메뉴 — 열기 · 업무 링크 복사 · 완료로 표시 · 삭제
  • 댓글 — 카드의 💬 N을 한 번 누르면 댓글 대화창이 열립니다. (16장)
  • @@ -707,6 +708,7 @@
    • 구역 이름 옆 +는 그 구역 끝에 줄을 추가합니다. 표 아래 + 구역 추가로 새 구역을 만듭니다.
    • 항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.
    • +
    • 끌어서 순서 바꾸기 — 항목 칸을 잡고 위아래로 끌면 그 줄(항목 칸으로 묶인 줄·세로 병합 포함)이 마우스를 따라 다른 항목 사이로 바로 옮겨 가고, 놓으면 저장됩니다. 같은 구역 안에서만 움직이며 Esc는 취소. 살짝 누르기만 하면 예전처럼 이름 수정입니다.
    • 주요 업무 칸을 우클릭해 위에 줄 추가 · 아래에 줄 추가를 하면 항목 칸은 그대로 두고 그 항목 안에 줄이 늘어납니다(줄마다 주요 업무·정량 목표는 따로). 같은 메뉴의 줄 삭제는 그 한 줄만 지웁니다. 묶인 항목 칸은 항목 칸 메뉴의 항목 칸 나누기로 다시 나눕니다. 줄을 추가·삭제하면 새로고침 없이 표가 그 자리에서 움직이며 바뀝니다.
    • 구역 순서 — 첫 열 구분 칸을 우클릭하거나 마우스를 올려 나오는 ⋯를 누르면 구역 위로 · 구역 아래로 · 구역 끝에 줄 추가가 나옵니다. 구역 안의 줄 순서·병합은 그대로 함께 옮겨지고, 다음에 만드는 회의록도 바뀐 순서를 이어받습니다(회의 완료 전까지, 누구나).
    • 줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.
    • diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index b1d78fd..03c2eb2 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -106,5 +106,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index 7ce2a32..903ebfe 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index 931c838..ebed856 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index 503f216..8a81eb8 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -472,5 +472,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index b76ec5c..02e938b 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/static/performance.css b/app/static/performance.css index 972f66b..5440bfc 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -352,3 +352,17 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; } .perf-prog-cancel[hidden] { display: none; } .perf-prog-cancel:disabled { opacity: .6; cursor: default; } + +/* ── 매출 칸 아래 광고비(ROAS%) — 광고비 화면 색(--perf-ad), 카페24 는 구글·메타 두 줄(2026-10-19) ── */ +.perf-adl { display: block; margin-top: 1px; font-size: 11px; line-height: 1.35; font-weight: 600; color: var(--perf-ad); white-space: nowrap; } +.perf-adl i { margin-right: 3px; font-style: normal; font-weight: 500; opacity: .8; } +.perf-adl em { margin-left: 1px; font-style: normal; font-weight: 500; opacity: .85; } +.perf .perf-main td.is-editing .perf-adl { visibility: hidden; } +.perf-adl-note { display: inline-flex; align-items: center; gap: 5px; color: var(--perf-ad); font-weight: 600; } +.perf-adl-key { width: 10px; height: 10px; border-radius: 3px; background: var(--perf-ad); } +.perf-unit-note { margin-left: 4px; } +.perf-unit-suffix { margin-left: 2px; font-size: .55em; font-weight: 600; color: var(--color-midtone-gray, #777); } +/* 보기 설정(매출 단위) */ +.perf-opt-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.perf-opt-label { font-weight: 600; } +.perf-head-notes { display: inline-flex; align-items: center; gap: 12px; margin-right: auto; margin-left: 12px; font-size: 12px; } diff --git a/app/static/performance.js b/app/static/performance.js index ab8a40b..5cf2014 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -24,6 +24,13 @@ } function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); } function won(n) { return n ? fmt(n) : '–'; } + // 매출 단위(실적 설정 "보기 설정", 쿠키 perf_unit) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리) + function unitWon(n, unit) { + if (!n) return won(0); + if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR"); + if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 }); + return fmt(n); + } // 축 눈금용 짧은 금액(1.2억 / 350만) function short(n) { const a = Math.abs(n), s = n < 0 ? "-" : ""; @@ -582,7 +589,7 @@ td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")" : "눌러 " + MANUAL_WORD + " 직접 입력"; const g = td.querySelector(".v-gross"); - if (g) g.innerHTML = won(res.amount); + if (g) g.innerHTML = unitWon(res.amount, data.unit); td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산 manualDirty = true; return true; @@ -745,6 +752,21 @@ // 설정 // ════════════════════════════════════════════════════ function initSettings(root) { + // 보기 설정 — 매출 단위(원·천원·백만원)를 이 브라우저 쿠키에(1년). 매출 실적 화면을 다시 열면 적용 + const UNIT_EX = { won: "2,475,300", thousand: "2,475", million: "2.5" }; + root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (b) { + b.addEventListener("click", function () { + const u = b.dataset.unit; + document.cookie = "perf_unit=" + u + "; path=/performance; max-age=31536000; SameSite=Lax"; + root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (x) { + x.classList.toggle("is-active", x === b); + x.setAttribute("aria-checked", x === b ? "true" : "false"); + }); + const ex = document.getElementById("perf-unit-example"); + if (ex) ex.textContent = "예: 2,475,300원 → " + UNIT_EX[u]; + }); + }); + // 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림 root.querySelectorAll(".perf-switch input").forEach(function (box) { box.addEventListener("change", async function () { @@ -950,446 +972,6 @@ } finally { btn.disabled = false; btn.textContent = label; } } - // ── 카페24 매출 대조 — 카페24 "일별 매출내역" 열 순서대로 ── - let lastShop = {}; // 일별 비교에 붙여넣은 카페24 값(날짜 → 열) — 대조 표에 차이 열로 표시 - const recon = document.getElementById("perf-recon"); - if (recon) recon.addEventListener("click", async function () { - const day = document.getElementById("perf-recon-date").value; - const out = document.getElementById("perf-recon-result"); - if (!day) return; - recon.disabled = true; - out.innerHTML = '

      카페24에서 불러오는 중…

      '; - try { - const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day)); - if (!r.ok) { out.innerHTML = '

      ' + esc((r.label ? r.label + " — " : "") + r.message) + "

      "; return; } - const s = r.orders.self, m = r.orders.market, rs = r.refunds.self, rm = r.refunds.market; - const dev = function (n, amt) { return n ? fmt(n) + '건 ' + won(amt) + "" : won(0); }; - const MARKET_NAMES = {}; - root.querySelectorAll("tr[data-code]").forEach(function (tr) { MARKET_NAMES[tr.dataset.code] = tr.dataset.name; }); - const disc = ["membership_discount_amount", "set_product_discount_amount", "app_discount_amount", - "market_other_discount_amount", "shipping_fee_discount_amount"]; - const coup = ["coupon_discount_price", "coupon_shipping_fee_amount"]; - const LABEL = { - membership_discount_amount: "회원할인", set_product_discount_amount: "세트상품할인", app_discount_amount: "앱할인", - market_other_discount_amount: "마켓 기타할인", shipping_fee_discount_amount: "배송비할인", - coupon_discount_price: "상품쿠폰", coupon_shipping_fee_amount: "배송비쿠폰", - }; - const sum = function (g, keys) { return keys.reduce(function (a, k) { return a + (g[k] || 0); }, 0); }; - // x[4] = 붙여넣은 카페24 일별 매출내역 열 번호(일별 비교에서 이 날짜를 눌렀을 때 차이 표시) - const rows = [ - ["주문수", s.orders, m.orders, "cnt", 0], ["품목수(수량 합계)", s.items, m.items, "cnt", 1], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt", 1], - ["상품구매금액", s.order_price_amount, m.order_price_amount, "", 2], - ["배송비", s.shipping_fee, m.shipping_fee, "", 3], - ["할인 합계", sum(s, disc), sum(m, disc), "", 4], - ].concat(disc.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; })) - .concat([["쿠폰 합계", sum(s, coup), sum(m, coup), "", 5]]) - .concat(coup.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; })) - .concat([ - [" 참고식: 상품구매금액 + 배송비 − 할인 − 쿠폰", s.goods_total, m.goods_total, "sub"], - ["실결제금액", s.payment_amount, m.payment_amount, "", 6], - ["적립금 사용", s.points_spent_amount, m.points_spent_amount, "", 7], - ["예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "", 8], - ["네이버포인트", s.naver_point, m.naver_point, "", 9], - ["결제합계(실결제 + 적립금 + 예치금 + 네이버포인트)", s.total, m.total, "key", 10], - ["환불 건수(환불 목록)", rs.count, rm.count, "cnt"], - [" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"], - [" · 적립금 환불", rs.used_points, rm.used_points, "sub"], - [" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"], - ["환불 목록 없는 네이버페이 취소·반품 품목 수", rs.no_record_count, rm.no_record_count, "cnt"], - [" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"], - ["환불합계", rs.total, rm.total, "key", 11], - ["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12], - ]); - const shopCols = (lastShop[r.date] || {}).cols || null; - out.innerHTML = '" + - (shopCols ? "" : "") + "" + - rows.map(function (x) { - const cls = x[3] === "key" ? ' class="perf-row-week"' : ""; - const f = function (v) { return x[3] === "cnt" ? fmt(v) : won(v); }; - let cmp = ""; - if (shopCols) { - const both = (x[1] || 0) + (x[2] || 0), c = x[4] == null ? null : shopCols[x[4]]; - cmp = '"; - } - return "" + cmp + ""; - }).join("") + "
      ' + esc(r.date) + - "카페24 열(자체몰 채널)다른 쇼핑몰 열(외부 마켓)합계카페24 화면차이
      ' + f(both) + '' + (c == null ? "" : f(c)) + '' + - (c == null ? "" : both === c ? '✓' : '' + (both > c ? "+" : "") + fmt(both - c) + "") + "' + esc(x[0]) + - '' + f(x[1]) + '' + f(x[2]) + "
      " + - (r.refund_basis - ? (function () { - const b = r.refund_basis; - const row = function (label, x, cls) { - return "' + label + '' + - fmt(x.count) + '' + won(x.actual_refund_amount) + '' + - won(x.used_points + x.used_credits) + '' + won(x.with_points) + ""; - }; - return '

      환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요

      ' + - '' + - "" + - row("환불완료일 기준 · 완료 적용(합계 포함 칸)", b.completed, "perf-row-week") + - row("환불접수일 기준 · 전체 상태", b.accepted_all) + - (b.by_pay_date ? row("결제일 기준 · 그날 결제한 주문의 환불(오늘까지" + - (b.by_pay_date.refund_dates.length ? ", 환불일 " + esc(b.by_pay_date.refund_dates.join(", ")) : "") + ")", b.by_pay_date) : "") + - (b.accepted_by_status || []).map(function (s) { - return row(" · 접수일 기준 " + esc(s.label), s); - }).join("") + "
      기준건수실제 환불액적립금·예치금 환불합계(포함)
      "; - })() - : "") + - ((r.refund_candidates || []).length - ? '

      환불합계 후보 — 카페24 화면 값을 넣으면 같은 줄을 표시합니다

      ' + - '
      ' + - '' + - r.refund_candidates.map(function (c) { - return ''; - }).join("") + "
      후보금액차이
      ' + esc(c.label) + '' + - won(c.amount) + '–
      " - : "") + - ((r.refund_list || []).length - ? '

      환불 건별 (환불 API)

      ' + - '' + - '' + - "" + - r.refund_list.map(function (x) { - const st = { T: "환불완료", F: "환불전", M: "환불보류" }[x.status] || x.status; - return '"; - }).join("") + "
      환불코드주문번호채널상태접수일완료일수량실제 환불액적립금·예치금환불수단
      ' + esc(x.refund_code) + "" + esc(x.order_id) + "" + esc(x.channel || "–") + - "" + esc(st) + "" + esc(x.accepted_date || "–") + "" + esc(x.refund_date || "–") + - '' + fmt(x.quantity) + '' + won(x.actual_refund_amount) + - '' + won(x.used_points + x.used_credits) + "" + esc((x.methods || []).join(", ") || "–") + "
      " - : "") + - ((r.no_record_claims || []).length - ? '

      환불 목록에 없는 네이버페이 취소·반품 (환불합계에 넣은 건 — 주문 전체취소면 배송비 포함)

      ' + - '' + - '' + - "" + - r.no_record_claims.map(function (c) { - return '"; - }).join("") + "
      주문번호품목채널상태반영일상품수량뺀 금액품목 결제금액쿠폰주문 전체취소주문 배송비
      ' + esc(c.order_id) + "" + esc(c.item_code) + "" + esc(c.place_name || c.market_id || "–") + - "" + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + "" + esc(c.day) + - "" + esc(c.product_name) + '' + fmt(c.quantity) + '' + won(c.amount) + - (c.shipping_refund ? ' (배송비 ' + fmt(c.shipping_refund) + ")" : "") + - '' + won(c.item_payment_amount) + '' + won(c.coupon) + "" + - (c.order_all_claimed ? "예" : "아니오") + '' + won(c.order_shipping_fee) + "
      " - : "") + - ((r.reduced_orders || []).length - ? '

      그날 결제한 주문 중 금액이 줄어든 주문 (취소·반품) — "환불 기록 없음"이 환불 API 에 안 잡힌 건

      ' + - '' + - '' + - "" + - r.reduced_orders.map(function (x) { - const miss = x.diff - x.refunded; - return " 0 ? ' class="perf-row-match"' : "") + '>"; - }).join("") + "
      주문번호채널결제수단품목 상태취소·환불일결제 당시현재줄어든 금액환불 기록
      ' + esc(x.order_id) + "" + - esc(x.channel || "–") + "" + esc(x.payment || "–") + "" + - esc(x.statuses.join(", ") + (x.naver_pay.length ? " / 네이버페이 " + x.naver_pay.join(",") : "")) + "" + - esc(x.claim_dates.join(", ") || "–") + '' + won(x.initial) + '' + - won(x.now) + '' + won(x.diff) + '' + - (x.refunded ? won(x.refunded) + ' ' + esc(x.refund_dates.join(", ")) + "" : "없음") + "
      " - : "") + - (r.claims - ? '

      그날 취소·반품·교환 완료 품목 (주문 API)

      ' + - ((r.claims.errors || []).length ? '

      ' + esc(r.claims.errors.join(" / ")) + "

      " : "") + - ((r.claims.items || []).length - ? '' + - '' + - "" + - r.claims.items.map(function (c) { - return ""; - }).join("") + "
      조회주문번호채널상태클레임상품수량판매가×수량품목 결제금액쿠폰환불 기록
      ' + esc(c.via) + "" + esc(c.order_id) + - "" + esc(c.channel || "–") + "" + esc(c.status + (c.status_text ? " " + c.status_text : "")) + - "" + esc(c.claim_code || "–") + "" + esc(c.product_name) + '' + fmt(c.quantity) + - '' + won(c.product_amount) + '' + won(c.payment_amount) + - '' + won(c.coupon) + "" + (c.has_refund ? "있음" : '없음') + "
      " + - '

      전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) + - '. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).

      ' - : '

      없음

      ') - : "") + - ((r.by_channel || []).length - ? '

      주문 채널별

      ' + - '' + - '' + - "" + - r.by_channel.map(function (b) { - const col = MARKET_NAMES[b.target] || b.target; - const kind = b.kind === "self" ? "자체몰 채널" + (b.label ? "(" + b.label + ")" : "") - : b.kind === "market" ? "외부 마켓" : '알 수 없는 채널'; - return '"; - }).join("") + "" + - // 카페24 열(자체몰) 기기 합계 - (function () { - const own = r.by_channel.filter(function (b) { return b.target === "cafe24"; }); - const t = own.reduce(function (a, b) { - a.o += b.orders; a.t += b.total; a.po += b.pc_orders; a.pt += b.pc_total; a.mo += b.mobile_orders; a.mt += b.mobile_total; - a.ra += b.refund_amount; return a; - }, { o: 0, t: 0, po: 0, pt: 0, mo: 0, mt: 0, ra: 0 }); - return '"; - })() + "
      market_id주문경로구분반영 열주문수결제합계PC 주문모바일 주문환불순매출
      ' + esc(b.market_id) + "" + esc(b.place || "–") + - (b.place_id && b.place_id !== b.place ? ' ' + esc(b.place_id) + "" : "") + - "" + (b.kind === "unknown" ? kind : esc(kind)) + "" + esc(col) + - '' + fmt(b.orders) + '' + won(b.total) + - '' + dev(b.pc_orders, b.pc_total) + '' + dev(b.mobile_orders, b.mobile_total) + - '' + won(-b.refund_amount) + '' + won(b.total - b.refund_amount) + "
      카페24 열(자체몰) 합계' + - fmt(t.o) + '' + won(t.t) + '' + dev(t.po, t.pt) + - '' + dev(t.mo, t.mt) + '' + won(-t.ra) + - '' + won(t.t - t.ra) + "
      " + - '

      한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' + - 'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.

      ' - : "") + - ((r.by_payment || []).length - ? '

      결제수단별 (카페24 열)

      ' + - '' + - (function () { - const tot = r.by_payment.reduce(function (a, p) { return a + p.total; }, 0); - return r.by_payment.map(function (p) { - return '"; - }).join(""); - })() + "
      결제수단주문수결제합계비중
      ' + esc(p.method) + '' + fmt(p.orders) + - '' + won(p.total) + '' + - (tot > 0 ? (p.total / tot * 100).toFixed(1) + "%" : "–") + "
      " - : "") + - (r.diag - ? (function () { - // 판매가 합계 − 카페24 상품구매금액 = 찾는 금액(예: 9/23 → 62). 같은 값인 필드를 강조. - const gap = shopCols ? (s.order_price_amount + m.order_price_amount) - shopCols[2] : null; - const PART = { initial: "주문 금액(결제 당시 initial_order_amount)", actual: "주문 금액(현재 actual_order_amount)", - item: "품목(items) 합계", order: "주문 최상위 필드" }; - const cells = ["initial", "actual", "item", "order"].map(function (p) { - const f = r.diag[p] || {}; - const keys = Object.keys(f).filter(function (k) { return f[k]; }); - return '
      ' + esc(PART[p]) + "
      " + - (keys.length ? '' + keys.map(function (k) { - return ""; - }).join("") + "
      ' + esc(k) + - '' + fmt(f[k]) + "
      " : '

      0 아닌 값 없음

      ') + "
      "; - }).join(""); - const odd = (r.odd_orders || []).map(function (o) { - return '' + esc(o.order_id) + "" + esc(o.channel || "–") + '' + - fmt(o.items_gross) + '' + fmt(o.order_price_amount) + '' + fmt(o.total) + - '' + o.items.map(function (i) { - return esc(i.code + " " + i.status + " ×" + i.quantity + " — " + - Object.keys(i.fields).map(function (k) { return k + "=" + fmt(i.fields[k]); }).join(", ")); - }).join("
      ") + ""; - }).join(""); - return '

      원본 금액 필드 합계 (진단 — 그날 결제 주문 전체)' + - (gap ? ' · 판매가 합계 − 카페24 상품구매금액 = ' + fmt(gap) + " (같은 값 강조)" : "") + "

      " + - '
      ' + cells + "
      " + - (odd ? '

      상품금액이 100원 단위가 아니거나 판매가×수량 합과 다른 주문

      ' + - '' + - '' + odd + "
      주문번호채널판매가×수량주문 상품금액결제합계(계산)품목 금액 필드(0 제외)
      " : ""); - })() - : "") + - '

      ' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) + - "건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.

      "; - const target = document.getElementById("perf-recon-target"); - if (target) target.addEventListener("input", function () { - const v = parseInt(target.value.replace(/[^0-9-]/g, ""), 10); - out.querySelectorAll("#perf-recon-cands tr[data-amount]").forEach(function (tr) { - const a = parseInt(tr.dataset.amount, 10); - const d = tr.querySelector(".perf-cand-diff"); - if (isNaN(v)) { d.textContent = "–"; tr.classList.remove("perf-row-match"); return; } - d.textContent = a === v ? "일치" : fmt(a - v); - tr.classList.toggle("perf-row-match", a === v); - }); - }); - } catch (err) { - out.innerHTML = '

      ' + esc(err.message) + "

      "; - } finally { recon.disabled = false; } - }); - - // ── 일별 한 번에 비교 — 카페24 일별 매출내역 붙여넣기 ↔ 저장값 ↔ 지금 API 값 ── - // 붙여넣은 한 줄: "2026-09-29(화) 주문수 품목수 … 결제합계 환불합계 순매출" — 뒤의 세 숫자와 첫 숫자(주문수)만 쓴다. - function parseDaily(text) { - const out = {}; - String(text || "").split(/\r?\n/).forEach(function (line) { - const m = line.match(/(\d{4})[-./](\d{2})[-./](\d{2})/); - if (!m) return; - const nums = (line.slice(m.index + m[0].length).match(/-?\d[\d,]*/g) || []) - .map(function (x) { return parseInt(x.replace(/,/g, ""), 10); }); - if (nums.length < 3) return; - const n = nums.length; - out[m[1] + "-" + m[2] + "-" + m[3]] = { orders: n >= 13 ? nums[0] : null, paid: nums[n - 3], refund: nums[n - 2], net: nums[n - 1], - cols: n >= 13 ? nums.slice(n - 13) : null }; - }); - return out; - } - const dailyBtn = document.getElementById("perf-daily-check"); - if (dailyBtn) dailyBtn.addEventListener("click", async function () { - const out = document.getElementById("perf-daily-result"); - const shop = lastShop = parseDaily(document.getElementById("perf-daily-paste").value); - const dates = Object.keys(shop).sort(); - if (!dates.length) { out.innerHTML = '

      날짜가 있는 줄을 찾지 못했습니다. 카페24 일별 매출내역 표를 복사해 붙여 넣으세요.

      '; return; } - const live = document.getElementById("perf-daily-live").checked; - dailyBtn.disabled = true; - out.innerHTML = '

      ' + (live ? "저장값과 카페24 API 값을 계산하는 중… (기간이 길면 1~2분)" : "저장값을 불러오는 중…") + "

      "; - try { - const from = dates[0], to = dates[dates.length - 1]; - const r = await api("GET", "/performance/api/marketplaces/cafe24/daily-check?from=" + from + "&to=" + to + (live ? "&live=1" : "")); - if (!r.ok) { out.innerHTML = '

      ' + esc(r.message) + "

      "; return; } - const byDate = function (rows) { const o = {}; (rows || []).forEach(function (x) { o[x.date] = x; }); return o; }; - const db = byDate(r.db), lv = r.live ? byDate(r.live) : null; - const zero = { paid: 0, refund: 0, orders: 0 }; - const diff = function (ours, theirs) { - const d = ours - theirs; - return d === 0 ? '✓' : '' + (d > 0 ? "+" : "") + fmt(d) + ""; - }; - const todayIso = today(); - let bad = 0, stale = 0, rule = 0; - const sum = { cp: 0, cr: 0, dp: 0, dr: 0, lp: 0, lr: 0 }; - const body = dates.slice().reverse().map(function (d) { - const c = shop[d], x = db[d] || zero, l = lv ? (lv[d] || zero) : null; - sum.cp += c.paid; sum.cr += c.refund; sum.dp += x.paid; sum.dr += x.refund; - if (l) { sum.lp += l.paid; sum.lr += l.refund; } - const dbOk = x.paid === c.paid && x.refund === c.refund; - const liveOk = l && l.paid === c.paid && l.refund === c.refund; - let verdict; - if (dbOk) verdict = '일치'; - else if (l && liveOk) { verdict = '다시 가져오면 해결'; stale++; } - else if (l) { - const what = [l.paid !== c.paid ? "결제" : "", l.refund !== c.refund ? "환불" : ""].filter(Boolean).join("·"); - verdict = '규칙 차이(' + what + ")"; rule++; - } else verdict = '차이'; - if (!dbOk) bad++; - const wd = "일월화수목금토"[new Date(d + "T00:00:00").getDay()]; - return "" + (d === todayIso ? ' 오늘·집계 중' : "") + "" + - '' + (c.orders == null ? "–" : fmt(c.orders)) + ' / ' + fmt(x.orders) + (l ? " / " + fmt(l.orders) : "") + "" + - '' + won(c.paid) + '' + diff(x.paid, c.paid) + "" + (l ? '' + diff(l.paid, c.paid) + "" : "") + - '' + won(c.refund) + '' + diff(x.refund, c.refund) + "" + (l ? '' + diff(l.refund, c.refund) + "" : "") + - "" + verdict + (x.synced_at ? '
      저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "
      " : "") + ""; - }).join(""); - const head = '날짜주문수 카페24 / 저장' + (lv ? " / API" : "") + "" + - "결제합계(카페24)저장값 차이" + (lv ? "API 차이" : "") + - "환불합계(카페24)저장값 차이" + (lv ? "API 차이" : "") + '판정'; - const foot = '합계' + won(sum.cp) + '' + - diff(sum.dp, sum.cp) + "" + (lv ? '' + diff(sum.lp, sum.cp) + "" : "") + '' + won(sum.cr) + - '' + diff(sum.dr, sum.cr) + "" + (lv ? '' + diff(sum.lr, sum.cr) + "" : "") + ""; - const summary = bad - ? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다") - : "모든 날짜가 일치합니다."; - out.innerHTML = '

      ' + esc(summary) + - (r.live_error ? "
      API 계산 실패: " + esc(r.live_error) : "") + "

      " + - (stale ? '
      " : "") + - '' + head + "" + body + "" + foot + "
      " + - '

      차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.

      '; - } catch (err) { - out.innerHTML = '

      ' + esc(err.message) + "

      "; - } finally { dailyBtn.disabled = false; } - }); - const dailyOut = document.getElementById("perf-daily-result"); - if (dailyOut) dailyOut.addEventListener("click", async function (e) { - const dayBtn = e.target.closest("[data-recon-day]"); - if (dayBtn && recon) { - document.getElementById("perf-recon-date").value = dayBtn.dataset.reconDay; - recon.click(); - recon.scrollIntoView({ behavior: "smooth", block: "center" }); - return; - } - const rs = e.target.closest("#perf-daily-resync"); - if (!rs) return; - if (!(await confirmMsg(rs.dataset.from + " ~ " + rs.dataset.to + " 카페24 매출을 지금 규칙으로 다시 가져옵니다."))) return; - rs.disabled = true; - rs.textContent = "가져오는 중…"; - try { - const res = await api("POST", "/performance/api/sync", { from: rs.dataset.from, to: rs.dataset.to, codes: ["cafe24"] }); - const r0 = (res.results || [])[0]; - if (r0 && !r0.ok) throw new Error((r0.label || r0.status) + ": " + (r0.message || "")); - dailyBtn.click(); - } catch (err) { - alertMsg("다시 가져오기 실패: " + err.message); - rs.disabled = false; - } - }); - - // ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑·쿠팡) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ── - const probe = document.getElementById("perf-probe"); - if (probe) probe.addEventListener("click", async function () { - const day = document.getElementById("perf-probe-date").value; - const out = document.getElementById("perf-probe-result"); - if (!day) return; - probe.disabled = true; - const codeSel = document.getElementById("perf-probe-code"); - const code = codeSel ? codeSel.value : "elevenst"; - const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)", - gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)", - coupang: "쿠팡에서 불러오는 중… (판매자배송 상태 6개 + 로켓그로스, 수십 초)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)"; - out.innerHTML = '

      ' + loading + "

      "; - try { - const to = document.getElementById("perf-probe-to").value || day; - const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) + - "&to=" + encodeURIComponent(to)); - if (!r.ok) { out.innerHTML = '

      ' + esc((r.label ? r.label + " — " : "") + r.message) + "

      "; return; } - // 원본 확인은 최대 31일 — 더 긴 기간을 넣으면 서버가 앞 31일만 본다. 실제 조회 기간을 꼭 보여 준다. - const shown = r.date ? (r.date === r.to ? r.date : r.date + " ~ " + r.to) : ""; - const cut = r.to && r.to < to; - const range = shown ? '

      조회 기간 ' + esc(shown) + "" + - (cut ? " — 원본 데이터 확인은 한 번에 31일까지라 " + esc(r.to) + " 뒤(~" + esc(to) + ")는 조회하지 않았습니다. " + - "1년치 매출은 위 [과거 매출 가져오기]로 받으세요(31일씩 나눠 불러 저장)." : "") + "

      " : ""; - const summary = range + '' + - '' + - r.probes.map(function (p) { - return '"; - }).join("") + "
      조회주소결과건수
      ' + esc(p.label) + '' + esc(p.path) + "" + - (p.ok ? '동작' : '실패 ' + esc(p.error) + "") + - '' + (p.ok ? fmt(p.count) : "") + "
      "; - const details = r.probes.filter(function (p) { return p.ok && p.count; }).map(function (p) { - return '

      ' + esc(p.label) + " — " + fmt(p.count) + "줄

      " + - '' + - '' + - p.fields.map(function (f) { - return '"; - }).join("") + "
      항목채워진 줄숫자 합계예시 값
      ' + esc(f.name) + '' + fmt(f.filled) + '' + - (f.sum == null ? "" : fmt(f.sum)) + "" + (f.personal ? '개인정보(숨김)' : esc(f.sample)) + "
      "; - }).join(""); - // 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교 - const days = (r.days || []).length ? '

      날짜별 현재 규칙 매출

      ' + - (r.rule ? '

      규칙: ' + esc(r.rule) + "

      " : "") + - '" + - "" + - r.days.map(function (d) { - return '"; - }).join("") + '' + - ["orders", "amount", "claimed", "ship"].map(function (k) { - return '"; - }).join("") + "
      날짜주문 수' + - esc((r.day_cols || {}).amount || "매출") + "" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "" + - esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "
      ' + esc(d.date) + '' + fmt(d.orders) + - '' + fmt(d.amount) + '' + fmt(d.claimed || 0) + - '' + fmt(d.ship || 0) + "
      합계' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "
      " : ""; - // 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모) - const rc = r.refund_candidates || []; - const candDays = (r.days || []).map(function (d) { return d.date; }); - const cands = rc.length ? '

      ' + esc(r.candidates_title || "환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불") + "

      " + - '' + - rc.map(function (c) { return ""; }).join("") + "" + - candDays.map(function (dt) { - return '" + rc.map(function (c) { - return '"; - }).join("") + ""; - }).join("") + '' + rc.map(function (c) { - if (c.error) return '"; - const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0); - return '"; - }).join("") + "
      날짜" + esc(c.label) + "
      ' + esc(dt) + "' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "
      합계실패 ' + esc(c.error) + "' + fmt(t) + "
      " + - rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) { - return '

      ' + esc(c.label) + " — " + fmt(c.rows.length) + "건

      " + - '' + - '' + - '' + - c.rows.map(function (x) { - return '"; - }).join("") + "
      환불일주문일주문번호주문상품금액메모
      ' + esc(x.date) + "" + esc(x.orderDate || "") + "" + - esc(x.orderId) + "" + esc(x.orderProductId) + - '' + fmt(x.amount) + '' + esc(x.note) + "
      "; - }).join("") : ""; - out.innerHTML = summary + days + cands + (details ||'

      그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.

      '); - } catch (err) { - out.innerHTML = '

      ' + esc(err.message) + "

      "; - } finally { probe.disabled = false; } - }); - // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ── const backfill = document.getElementById("perf-backfill"); if (backfill) backfill.addEventListener("click", async function () { diff --git a/app/static/project.css b/app/static/project.css index 4b25e67..b26969a 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -424,6 +424,19 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important; } .pj-card:hover { box-shadow: var(--pj-card-shadow-hover); transform: translateY(-1px); } .pj-card.is-dragging { opacity: .5; } +/* 카드 끌기 실시간 미리보기(2026-10-19) — 원래 카드는 숨기고 놓일 자리에 점선 자리 표시, + 끄는 모양은 살짝 기울어진 그림자 카드(setDragImage 용, 화면 밖에 잠깐 붙였다 뗀다). */ +.pj-card.is-drag-src { display: none; } +.pj-card-ph { + flex: none; box-sizing: border-box; border-radius: var(--pj-card-radius); + border: 2px dashed var(--pj-accent); background: var(--pj-accent-tint); + animation: pj-card-ph-in .16s ease-out; +} +@keyframes pj-card-ph-in { from { opacity: 0; } to { opacity: 1; } } +.pj-card-ghost { position: fixed; left: -10000px; top: 0; padding: 14px; pointer-events: none; } +.pj-card-ghost > .pj-card { + transform: rotate(2.5deg); box-shadow: 0 12px 28px rgba(0, 0, 0, .22); border-color: #c9c9cc; +} .pj-card.pj-tasknew { flex: none; min-height: 106px; box-sizing: border-box; border-color: #8b8c8d; cursor: default; } @@ -2908,10 +2921,11 @@ a.pj-meet-quick-done:hover { background: #e8f5ee; } .pj-meet-table { width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: var(--pj-text-size); - background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; color: var(--pj-ink); line-height: var(--pj-text-leading); + /* 테두리는 모두 검정(2026-10-19) — 바깥 아래선은 마지막 줄 칸 아래선이 대신한다(겹쳐 두꺼워지지 않게) */ + background: #fff; border: 1px solid #000; border-bottom: none; border-radius: 0; color: var(--pj-ink); line-height: var(--pj-text-leading); } .pj-meet-table th, .pj-meet-table td { - box-sizing: border-box; border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top; + box-sizing: border-box; border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 0; vertical-align: top; } .pj-meet-table tr > :last-child { border-right: none; } .pj-meet-table thead th { @@ -2935,9 +2949,13 @@ a.pj-meet-quick-done:hover { background: #e8f5ee; } .pj-meet-w-sec { width: 80px; } .pj-meet-w-label { width: 160px; } .pj-meet-w-amt { width: 122px; } -.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); } +.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); } .pj-meet-sec > tr > td.is-prev { background: #fafbfc; } -.pj-meet-sec > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); } +/* 항목 칸 끌어 옮기기 — 잡은 칸은 grab, 끄는 묶음은 연보라 + 왼쪽 보라 선, 끄는 동안 글자 선택 없음 */ +.pj-meet-sec th.pj-meet-c-label:has([data-meet-edit]) { cursor: grab; } +html.pj-meet-row-dragging, html.pj-meet-row-dragging * { cursor: grabbing !important; user-select: none !important; } +.pj-meet-table tr.is-meet-dragging > :not(.pj-meet-c-sec) { background-color: var(--pj-accent-tint) !important; } +.pj-meet-table tr.is-meet-dragging > th.pj-meet-c-label { box-shadow: inset 3px 0 0 var(--pj-accent); } .pj-meet-sec th { padding: 6px 8px; vertical-align: middle; text-align: center; } /* 구역·항목은 항상 세로 가운데 */ th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; vertical-align: middle; } .pj-meet-sec-add { diff --git a/app/static/project.js b/app/static/project.js index cd06427..c23e012 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -4746,26 +4746,31 @@ // 보드 드롭(전체보기) — 컬럼 이름(세션명)으로 옮긴다. 업무가 속한 '그 // 프로젝트'의 동일 이름 세션 id 를 찾아 적용(프로젝트마다 세션 id 가 다르다). function enableDropByName(body, name) { - body.addEventListener("dragover", function (e) { - if (!e.dataTransfer.types.includes("text/plain")) return; - e.preventDefault(); body.classList.add("is-over"); + // 전체 보기는 프로젝트마다 섹션이 달라 순서를 못 정한다 — 자리 표시는 섹션 맨 끝(제 섹션은 원래 자리) + wireCardPhOver(body, function () { return false; }); + // dragenter 도 받아 둔다 — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓아도 놓기가 거부되지 않게 + ["dragenter", "dragover"].forEach(function (kind) { + body.addEventListener(kind, function (e) { + if (!e.dataTransfer.types.includes("text/plain")) return; + e.preventDefault(); e.dataTransfer.dropEffect = "move"; + }); }); - body.addEventListener("dragleave", function () { body.classList.remove("is-over"); }); body.addEventListener("drop", async function (e) { if (!e.dataTransfer.types.includes("text/plain")) return; e.preventDefault(); - body.classList.remove("is-over"); const taskId = parseInt(e.dataTransfer.getData("text/plain"), 10); const t = tasks.find(function (x) { return x.id === taskId; }); - if (!t || (t.stage_name || "") === name) return; + if (!t || (t.stage_name || "") === name) { endCardDrag(true); return; } const plist = stagesByProject[t.project_id] || []; const target = plist.find(function (s) { return s.name === name; }); - if (!target) { alert("'" + (t.project_name || "이 프로젝트") + "' 에는 '" + name + "' 섹션이 없습니다."); return; } + if (!target) { endCardDrag(true); alert("'" + (t.project_name || "이 프로젝트") + "' 에는 '" + name + "' 섹션이 없습니다."); return; } + if (cardDrag) cardDrag.dropped = true; try { const res = await api("PUT", "/project/api/tasks/" + taskId, { stage_id: target.id }); mergeTask(res.task); - renderBoard(); } catch (err) { alert("이동 실패: " + err.message); } + endCardDrag(true); + renderBoard(); }); } @@ -5206,52 +5211,195 @@ } return cards.length; } - function enableDropByStageId(body, stageId) { - body.addEventListener("dragover", function (e) { - if (!e.dataTransfer.types.includes("text/plain")) return; - e.preventDefault(); body.classList.add("is-over"); + // ── 카드 끌기 실시간 미리보기(2026-10-19) — 끄는 동안 카드 자리는 비우고(자리 표시 + // .pj-card-ph), 마우스가 카드 사이를 지나는 순간 자리 표시가 그 사이로 옮겨 가며 다른 카드가 + // 미끄러지듯 비켜난다(FLIP 애니메이션). 놓으면 자리 표시가 있던 곳에 그대로 들어간다 — + // 섹션 안·다른 섹션 모두. 끄는 카드는 살짝 기울어진 그림자 카드로 마우스를 따라간다. + // 필터·정렬 중이거나 전체 보기(섹션 이름 보드)면 순서를 못 정하므로 원래 자리/섹션 맨 끝만. + let cardDrag = null; // { t, card, ph, fromBody, origIdx, dropped } + function phCards(body) { + return Array.prototype.filter.call(body.children, function (c) { + return c.classList.contains("pj-card") && c.dataset.taskId && (!cardDrag || c !== cardDrag.card); + }); + } + function phIndex(body) { // 자리 표시 앞에 있는 카드 수 = 놓을 자리 + const ph = cardDrag && cardDrag.ph; + if (!ph || ph.parentNode !== body) return -1; + return phCards(body).filter(function (c) { return c.compareDocumentPosition(ph) & Node.DOCUMENT_POSITION_FOLLOWING; }).length; + } + function startCardDrag(e, card, t) { + endCardDrag(true); + const body = card.parentNode; + if (!body || !body.classList.contains("pj-col-body")) return; + // 끄는 모양 — 카드 복제를 살짝 기울여 그림자와 함께(화면 배율 밖 body 에 잠깐 붙였다 뗀다) + try { + const r = card.getBoundingClientRect(); + const ghost = document.createElement("div"); + ghost.className = "pj-card-ghost"; + const clone = card.cloneNode(true); + clone.classList.remove("is-dragging"); + clone.style.width = card.offsetWidth + "px"; + ghost.appendChild(clone); + if (document.documentElement.classList.contains("pj-ui-scale")) ghost.style.zoom = "0.75"; + document.body.appendChild(ghost); + e.dataTransfer.setDragImage(ghost, Math.max(0, e.clientX - r.left) + 14, Math.max(0, e.clientY - r.top) + 14); + setTimeout(function () { ghost.remove(); }, 0); + } catch (_) {} + const ph = document.createElement("div"); + ph.className = "pj-card-ph"; + ph.style.height = card.offsetHeight + "px"; + // (cardDrag 를 정하기 전이라 phCards 에 끄는 카드도 들어 있다 — 그 순번 = 나머지 카드 중 원래 자리) + cardDrag = { t: t, card: card, ph: ph, fromBody: body, origIdx: phCards(body).indexOf(card), dropped: false }; + document.documentElement.classList.add("pj-card-dragging"); + // 끌기 그림이 찍힌 뒤에 원래 카드를 숨기고 그 자리에 자리 표시(같은 틱에 숨기면 크롬이 끌기를 취소) + const cur = cardDrag; + setTimeout(function () { + if (cardDrag !== cur || !card.isConnected) return; + card.parentNode.insertBefore(ph, card); + card.classList.add("is-drag-src"); + }, 0); + } + function endCardDrag(force) { + const d = cardDrag; + if (!d) return; + if (d.dropped && !force) return; // 놓은 뒤 저장 중 — 저장이 끝나면 다시 그리며 정리 + cardDrag = null; + document.documentElement.classList.remove("pj-card-dragging"); + d.ph.remove(); + d.card.classList.remove("is-drag-src", "is-dragging"); + document.querySelectorAll(".pj-col-body.is-over").forEach(function (b) { b.classList.remove("is-over"); }); + } + // 레이아웃 바꾸기 전후 위치 차이만큼 되돌렸다가 0 으로 — 비켜나는 카드가 미끄러지는 효과. + function flipBoardCards(bodies, mutate) { + const nodes = []; + bodies.forEach(function (b) { + if (!b) return; + Array.prototype.forEach.call(b.children, function (c) { + if ((c.classList.contains("pj-card") || c.classList.contains("pj-card-ph")) && nodes.indexOf(c) < 0) nodes.push(c); + }); + }); + const first = nodes.map(function (n) { const r = n.getBoundingClientRect(); return [r.left, r.top]; }); + mutate(); + nodes.forEach(function (n, i) { + if (!n.isConnected || n.classList.contains("is-drag-src")) return; + const r = n.getBoundingClientRect(); + const dx = first[i][0] - r.left, dy = first[i][1] - r.top; + if (!dx && !dy) return; + n.style.transition = "none"; + n.style.transform = "translate(" + dx + "px," + dy + "px)"; + }); + requestAnimationFrame(function () { + nodes.forEach(function (n) { + if (!n.style.transform) return; + n.style.transition = "transform .18s cubic-bezier(.2,.7,.3,1)"; + n.style.transform = ""; + setTimeout(function () { if (!n.style.transform) n.style.transition = ""; }, 220); + }); + }); + } + // 마우스 Y 가 이 섹션의 몇 번째 카드 사이인지 — 애니메이션 중인 카드는 움직이기 전 자리로 계산(떨림 방지). + function phTargetIndex(body, clientY, ordered) { + const cards = phCards(body); + if (!ordered) return body === cardDrag.fromBody ? Math.min(cardDrag.origIdx, cards.length) : cards.length; + for (let i = 0; i < cards.length; i++) { + const r = cards[i].getBoundingClientRect(); + let ty = 0; + if (cards[i].style.transform) { try { ty = new DOMMatrixReadOnly(getComputedStyle(cards[i]).transform).m42; } catch (_) {} } + if (clientY < r.top - ty + r.height / 2) return i; + } + return cards.length; + } + function placeCardPh(body, clientY, ordered) { + if (!cardDrag || !cardDrag.card.classList.contains("is-drag-src")) return; + const idx = phTargetIndex(body, clientY, ordered); + if (phIndex(body) === idx) return; + const ph = cardDrag.ph; + const oldBody = ph.parentNode; + flipBoardCards([oldBody, body], function () { + const cards = phCards(body); + if (idx < cards.length) body.insertBefore(ph, cards[idx]); + else if (cards.length) cards[cards.length - 1].after(ph); + else body.insertBefore(ph, body.querySelector(":scope > .pj-tasknew")); + }); + } + function wireCardPhOver(body, ordered) { + body.addEventListener("dragover", function (e) { + if (!cardDrag || !e.dataTransfer.types.includes("text/plain")) return; + placeCardPh(body, e.clientY, ordered()); + }); + } + function enableDropByStageId(body, stageId) { + wireCardPhOver(body, manualOrderAllowed); + // dragenter 도 받아 둔다 — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓아도 놓기가 거부되지 않게 + ["dragenter", "dragover"].forEach(function (kind) { + body.addEventListener(kind, function (e) { + if (!e.dataTransfer.types.includes("text/plain")) return; + e.preventDefault(); e.dataTransfer.dropEffect = "move"; + }); }); - body.addEventListener("dragleave", function () { body.classList.remove("is-over"); }); body.addEventListener("drop", async function (e) { if (!e.dataTransfer.types.includes("text/plain")) return; e.preventDefault(); - body.classList.remove("is-over"); const taskId = parseInt(e.dataTransfer.getData("text/plain"), 10); - const t = tasks.find(function (x) { return x.id === taskId; }); - if (!t) return; + const t = (cardDrag && cardDrag.t.id === taskId && cardDrag.t) || tasks.find(function (x) { return x.id === taskId; }); + if (!t) { endCardDrag(true); return; } + // 놓을 자리 = 자리 표시 위치(없으면 마우스 위치) + let idx = phIndex(body); + if (idx < 0) idx = cardDropIndex(body, e.clientY, taskId); + // 자리 표시 기준 이 섹션 카드 순서(끈 카드 포함) + 화면에 없는 이 섹션 업무는 뒤에 + const domIds = phCards(body).map(function (c) { return parseInt(c.dataset.taskId, 10); }) + .filter(function (id) { return id !== taskId; }); + domIds.splice(idx, 0, taskId); + function orderedFor() { + const rest = tasks.filter(function (x) { + return x.stage_id === stageId && x.context_project_id === projectId && domIds.indexOf(x.id) < 0; + }).map(function (x) { return x.id; }); + return domIds.concat(rest); + } if (t.stage_id === stageId) { if (!manualOrderAllowed()) { showToast("필터·정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (정렬: 기본, 필터 초기화 후 가능)", "error"); + endCardDrag(true); return; } // 같은 세션 안에서 카드 위치만 이동 — 세션 이동이 아니라 정렬. - const currentOrder = tasks.filter(function (x) { return x.stage_id === stageId; }); - const idx = cardDropIndex(body, e.clientY, taskId); - const withoutDragged = currentOrder.filter(function (x) { return x.id !== taskId; }); - withoutDragged.splice(idx, 0, t); - const orderedIds = withoutDragged.map(function (x) { return x.id; }); - const beforeIds = currentOrder.map(function (x) { return x.id; }); - if (beforeIds.join(",") === orderedIds.join(",")) return; // 놓은 자리가 원래 자리와 같으면 아무것도 안 함 + const beforeIds = tasks.filter(function (x) { return x.stage_id === stageId && x.context_project_id === projectId; }) + .map(function (x) { return x.id; }); + const orderedIds = orderedFor(); + if (beforeIds.join(",") === orderedIds.join(",")) { endCardDrag(true); return; } // 놓은 자리가 원래 자리와 같으면 아무것도 안 함 + if (cardDrag) cardDrag.dropped = true; // 저장하는 동안 놓은 자리 그대로 보인다 try { await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order", { ordered_ids: orderedIds }); applyStageOrder(stageId, orderedIds); - renderBoard(); } catch (err) { showToast("순서 변경 실패: " + err.message, "error"); } + endCardDrag(true); + renderBoard(); return; } + if (cardDrag) cardDrag.dropped = true; try { if (t.project_id === projectId) { const res = await api("PUT", "/project/api/tasks/" + taskId, { stage_id: stageId }); mergeTask(res.task); + // 다른 섹션에도 놓은 자리 그대로 — 기본 정렬·필터 없음일 때만 순서 저장(아니면 섹션 맨 끝) + if (manualOrderAllowed()) { + const orderedIds = orderedFor(); + try { + await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order", + { ordered_ids: orderedIds }); + applyStageOrder(stageId, orderedIds); + } catch (err) { showToast("섹션은 옮겼지만 순서 저장 실패: " + err.message, "error"); } + } } else { await api("POST", "/project/api/tasks/" + taskId + "/links", { project_id: projectId, stage_id: stageId }); t.stage_id = stageId; t.is_linked = true; } - renderBoard(); } catch (err) { showToast("이동 실패: " + err.message, "error"); } + endCardDrag(true); + renderBoard(); }); } @@ -6072,9 +6220,11 @@ e.dataTransfer.setData("text/plain", String(t.id)); // 왼쪽 프로젝트 목록에 놓으면 다른 프로젝트로 옮기기(원 소속 업무만 — 연결로 보이는 카드는 원 소속에서 옮긴다) if (t.context_project_id === t.project_id || !t.is_linked) e.dataTransfer.setData(TASK_DRAG_TYPE, String(t.id)); + e.dataTransfer.effectAllowed = "move"; card.classList.add("is-dragging"); + startCardDrag(e, card, t); }); - card.addEventListener("dragend", function () { card.classList.remove("is-dragging"); }); + card.addEventListener("dragend", function () { card.classList.remove("is-dragging"); endCardDrag(); }); // 세부 업무 줄을 이 카드에 놓으면 이 업무의 세부 업무로 옮긴다. // 원래 상위 업무 카드 위에서는 받지 않는다(제자리). card.addEventListener("dragover", function (e) { @@ -9625,6 +9775,8 @@ async function syncOnce() { // 회의록 패널을 보는 동안은 이전 프로젝트 화면의 자동 갱신이 왼쪽 메뉴를 다시 만들지 않게 한다. if (document.querySelector(".pj-meeting-panel-host")) return; + // 보드 카드를 끄는 중에는 다시 그리지 않는다(자리 표시·끄는 카드가 사라짐) — 다음 주기에 반영 + if (document.documentElement.classList.contains("pj-card-dragging")) return; if (syncing || observed === null || observed === applied) return; syncing = true; const target = observed; @@ -12381,6 +12533,115 @@ showContextMenu(x, y, items.concat(cellGrid ? [null].concat(cellGrid.widthItems(tr.querySelector("th.pj-meet-c-label"))) : [])); } + // ── 항목 칸 끌어 옮기기(2026-10-19) — 항목 칸을 잡고 위아래로 끌면 그 묶음(같은 항목 칸으로 이어 붙은 줄 + 걸친 세로 병합)이 + // 마우스를 따라 같은 구역의 묶음 사이로 실시간으로 옮겨 가고, 다른 줄은 미끄러지듯 비켜난다. 놓으면 move-to 저장 후 + // 표를 다시 그린다(실패하면 서버 순서로 되돌림). Esc = 취소. 살짝 누르기만 하면(5px 미만) 예전처럼 이름 수정. + if (canEdit) { + let press = null, rowDrag = null, noClickUntil = 0; + const meetUnits = function (tbody) { // 묶음 = 항목 칸 첫 줄부터(이어 붙은 줄·병합에 가려진 줄은 앞 묶음에) + const rows = Array.from(tbody.rows), covered = new Set(), out = []; + rows.forEach(function (tr, k) { + tr.querySelectorAll("td[data-meet-item]").forEach(function (td) { + for (let n = 1; n < (td.rowSpan || 1); n++) covered.add(k + n); + }); + }); + rows.forEach(function (tr, k) { + const start = !out.length || (tr.dataset.labelCont !== "1" && tr.querySelector("th.pj-meet-c-label") && !covered.has(k)); + if (start) out.push([tr]); else out[out.length - 1].push(tr); + }); + return out; + }; + const applyUnits = function (order) { // 줄을 이 순서로 다시 끼우고 FLIP(칸 단위 — 구분 칸은 첫 줄에 고정) + const d = rowDrag, cells = []; + d.tbody.querySelectorAll("tr > th, tr > td").forEach(function (c) { + if (c !== d.secTh) cells.push([c, c.getBoundingClientRect().top]); + }); + order.forEach(function (u) { u.forEach(function (tr) { d.tbody.appendChild(tr); }); }); + const first = d.tbody.rows[0]; + if (d.secTh && d.secTh.parentElement !== first) first.insertBefore(d.secTh, first.firstChild); + d.units = order; + if (!Element.prototype.animate) return; + cells.forEach(function (p) { + const dy = p[1] - p[0].getBoundingClientRect().top; + if (Math.abs(dy) > 0.5) { + p[0].animate([{ transform: "translateY(" + dy + "px)" }, { transform: "none" }], + { duration: 170, easing: "cubic-bezier(.2,.7,.3,1)" }); + } + }); + }; + const endRowDrag = function (cancel) { + const d = rowDrag; + rowDrag = null; + press = null; + if (!d) return null; + if (cancel && d.tbody.isConnected) { rowDrag = d; applyUnits(d.start); rowDrag = null; } + d.me.forEach(function (tr) { tr.classList.remove("is-meet-dragging"); }); + document.documentElement.classList.remove("pj-meet-row-dragging"); + noClickUntil = Date.now() + 350; + return d; + }; + table.addEventListener("mousedown", function (e) { + if (e.button !== 0 || rowDrag) return; + const th = e.target.closest("tbody.pj-meet-sec th.pj-meet-c-label"); + if (!th || e.target.closest("button, .is-editing, .pj-meet-colresize")) return; + press = { th: th, x: e.clientX, y: e.clientY }; + }); + document.addEventListener("mousemove", function (e) { + if (!press) return; + if (!rowDrag) { + if (Math.abs(e.clientY - press.y) < 5 || !press.th.isConnected) return; + const tr = press.th.parentElement, tbody = tr.closest("tbody"); + const units = meetUnits(tbody); + const me = units.find(function (u) { return u.indexOf(tr) >= 0; }); + if (!me || units.length < 2) { press = null; return; } + rowDrag = { tbody: tbody, units: units, start: units.slice(), me: me, secTh: tbody.querySelector("th.pj-meet-c-sec") }; + me.forEach(function (r) { r.classList.add("is-meet-dragging"); }); + document.documentElement.classList.add("pj-meet-row-dragging"); + try { window.getSelection().removeAllRanges(); } catch (_) {} + } + e.preventDefault(); + const d = rowDrag; + if (!d.tbody.isConnected) { endRowDrag(false); return; } // 그 사이 표를 다시 그림 + const others = d.units.filter(function (u) { return u !== d.me; }); + let idx = others.length; + for (let i = 0; i < others.length; i++) { + const top = others[i][0].getBoundingClientRect().top; + const bottom = others[i][others[i].length - 1].getBoundingClientRect().bottom; + if (e.clientY < (top + bottom) / 2) { idx = i; break; } + } + const order = others.slice(); + order.splice(idx, 0, d.me); + if (order.every(function (u, k) { return u === d.units[k]; })) return; + applyUnits(order); + }); + document.addEventListener("mouseup", function () { + const d = endRowDrag(false); + if (!d || !d.tbody.isConnected) return; + const k = d.units.indexOf(d.me); + if (k === d.start.indexOf(d.me)) return; // 제자리 + const next = d.units[k + 1]; + const moveId = d.me[0].dataset.item, before = next ? parseInt(next[0].dataset.item, 10) : null; + run(async function () { + try { + await api("POST", itemUrl(moveId) + "/move-to", { before_item_id: before }); + } catch (err) { + showToast("옮기지 못했습니다: " + err.message, "error"); + await refreshMeeting(); // 서버 순서로 되돌림 + return false; + } + return true; + }); + }); + document.addEventListener("keydown", function (e) { + if (e.key === "Escape" && rowDrag) { e.preventDefault(); e.stopPropagation(); endRowDrag(true); } + }, true); + window.addEventListener("blur", function () { if (rowDrag) endRowDrag(true); else press = null; }); + // 끌기를 끝낸 바로 뒤 클릭은 이름 수정으로 넘기지 않는다 + table.addEventListener("click", function (e) { + if (Date.now() < noClickUntil) { e.preventDefault(); e.stopImmediatePropagation(); } + }, true); + } + // ── 줄 구조가 바뀐 뒤(줄 추가·삭제·이동·항목 칸 나누기·구역 이동·셀 병합) 새로고침 없이 표의 구역 부분만 서버에서 다시 받아 // 그 자리에서 바꿔 끼운다(연간 목표 refreshTable 과 같은 방식) — 지운 줄은 흐려지며 사라지고, 남은 줄은 예전 자리에서 // 새 자리로 미끄러지고(FLIP), 새 줄은 위에서 내려오며 잠깐 강조. 동작 줄이기 설정이면 애니메이션 없이. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 6264b8b..a7e0346 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -352,6 +352,18 @@ ## 7. 화면 +- **2026-10-19 변경** + - **설정 진단 카드 삭제** — "쇼핑몰 원본 데이터 확인"·"카페24 매출 대조"·"일별 한 번에 비교" 카드와 그 화면 스크립트를 뺐다 + (사용자 요청 — 쇼핑몰별 규칙 대조가 끝나 더 안 씀). 서버 API `GET /api/marketplaces/{code}/reconcile`·`daily-check` 와 + 어댑터 `reconcile`은 다시 대조가 필요할 때를 위해 남겼다(화면 진입점 없음). 아래 절의 "원본 데이터 확인"·"매출 대조" 설명은 그 당시 기록. + - **보기 설정 · 매출 단위** — 설정 화면 "보기 설정" 카드(모듈 권한자 누구나): 원·천원·백만원. 이 브라우저 쿠키 `perf_unit`(1년, path `/performance`)에 두고 + 매출 실적 화면을 서버가 그 단위로 그린다(`dashboard.amount_text` — 천원 = 정수 반올림, 백만원 = 소수 한 자리, `router._unit_ctx` → 템플릿 `amt`·`money`). + 표·월/연 누적 카드 머리에 "단위: 천원", KPI·연 누적은 "3,835천원". 수동 입력은 늘 원 단위로 넣는다(입력 직후 칸은 JS `unitWon`). 광고비 탭·그래프 말풍선은 원 그대로. + - **매출 칸 아래 광고비(ROAS%)** — 일자별 × 쇼핑몰 표의 매출 칸마다 그 쇼핑몰 광고비와 ROAS 를 광고비 색(`--perf-ad`) 작은 줄로(`dashboard._ad_lines`). + 값은 광고비 탭과 같다(`ad_spend.channel_roas` — 구글·메타·네이버는 보고서 ROAS, 나머지는 그 쇼핑몰 매출 ÷ 광고비). 쇼핑몰 → 채널(`sales_ad_channels`): + 카페24 = **구글·메타 두 줄**("구글 100,000(413%)"), 네이버 = 네이버 광고, 쿠팡 = 쿠팡(윙), 그 밖은 같은 코드 채널. 일 합계 칸 = 보이는 쇼핑몰 광고비 합(ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합), + 주간합계·기간 합계 행도 그 기간 값. 광고비가 없는 칸은 줄 없음, 광고비 표(005) 미적용·조회 실패면 줄 없이 매출만. 총매출·수수료·차감 매출 전환과 무관하게 늘 보인다. + - **탭**(2026-10-13): 왼쪽 위 큰 탭 둘 — [매출 실적](검정, `/performance/`) · [광고비](주황, `/performance/ads`) — 아이콘 + 고른 탭 색으로 구분, 설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols `settings`, `/performance/settings`). `_tabs.html`. - **광고비** `/performance/ads?period=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널, diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index dbf3ae3..e500ff5 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -1384,6 +1384,24 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame - 검증: `tests/test_project_module.py::test_review_meeting_apply_is_one_transaction`(실제 PostgreSQL — 테스트 전용 트리거로 연결 실패 주입, 풀 1개, 줄 바뀜 409), 기존 `test_review_meeting_quick_tasks_shared`(동시 4건), `tests/js/goals_meeting_ui.test.js` [2g9]. +## 6-23. 보드 카드 끌기 실시간 미리보기 · 회의록 항목 칸 끌어 옮기기 · 회의록 표 검정 테두리 (2026-10-19, 마이그레이션 없음) + +- **보드 카드 끌기**(`project.js` `startCardDrag`·`placeCardPh`·`flipBoardCards`·`endCardDrag`) — 네이티브 HTML5 DnD 그대로(왼쪽 프로젝트 목록 이동 6-18·세부 업무 끌기와 같은 이벤트). + - dragstart: 카드 복제를 `.pj-card-ghost`(body 에 잠깐, 화면 배율이면 zoom .75) 안에서 2.5° 기울여 `setDragImage`. 다음 틱에 원래 카드를 `.is-drag-src`(display none)로 숨기고 + 그 자리에 같은 높이의 점선 자리 표시 `.pj-card-ph`(같은 틱에 숨기면 크롬이 끌기를 취소). + - dragover(섹션 body): 마우스 Y 가 카드 중간선 위/아래 어디인지(애니메이션 중인 카드는 transform 을 빼고 계산 — 떨림 방지)로 자리 표시를 옮기고, 옮기기 전후 위치 차이로 + FLIP(transform .18s) — 다른 카드가 미끄러지듯 비켜난다. 섹션을 넘어가도 같음. 순서를 못 정하는 경우(필터·정렬 중, 전체 보기 섹션 이름 보드)는 제 섹션 = 원래 자리, 다른 섹션 = 맨 끝. + - drop: 자리 표시 위치 = 놓을 자리. 같은 섹션 = `PUT stages/{id}/tasks/order`, 다른 섹션 = `PUT tasks/{id} {stage_id}` 뒤 그 섹션 `tasks/order`(기본 정렬·필터 없음일 때만, + 화면 카드 순서 + 화면에 없는 그 섹션 업무는 뒤). 멀티호밍 연결 업무는 예전처럼 links 만(순서 저장 없음). 저장하는 동안 놓은 모양 유지(`dropped`) → 끝나면 `renderBoard`. + - 섹션 밖에 놓거나 취소하면 dragend 가 자리 표시를 지우고 카드를 원래 자리에 다시 보인다. 끄는 동안 `html.pj-card-dragging` — 실시간 동기화(`syncOnce`)가 보드를 다시 그리지 않는다(다음 주기 반영). + - **body 는 dragenter 도 preventDefault** — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓으면 drop 이 거부되던 문제(Playwright 실제 크롬으로 재현). +- **회의록 항목 칸 끌어 옮기기** — 항목(`th.pj-meet-c-label`)을 마우스로 5px 이상 끌면 시작(그보다 짧으면 이름 수정 클릭 그대로, 끈 뒤 클릭은 막음). + - 묶음 = 항목 칸 첫 줄부터 이어 붙은 줄(`data-label-cont`)·주요 업무 세로 병합에 가려진 줄까지(서버 `move_meeting_group` 과 같은 경계). 묶음이 둘 이상인 구역만. + - 끄는 동안 그 묶음 tr 을 다른 묶음 중간선 기준으로 바로 옮겨 끼우고(구분 칸 `th.pj-meet-c-sec` 은 늘 구역 첫 줄로 옮김), 칸 단위 FLIP(`Element.animate` .17s). 끄는 줄은 연보라 + 왼쪽 보라 선. + - 놓으면 `POST /api/goals/meeting-items/{id}/move-to {before_item_id: 다음 묶음 첫 줄 | null = 구역 맨 끝}` → `refreshMeeting`. 실패하면 안내 후 서버 순서로 다시 그림. Esc = 원래 순서로. + - `db.move_meeting_group`: 같은 주 잠금(`_locked_meeting_items`, 회의 완료면 409)·묶음째·같은 구역만(다른 구역 400)·묶음 사이 자리(`before` 가 묶음 첫 줄이 아님) 409·제자리면 그대로. 권한은 줄 순서와 같음(누구나, 완료 전). +- **회의록 표 테두리** — `.pj-meet-table` 바깥·칸 테두리 모두 `#000`(예전 연회색). 칸은 오른쪽·아래 선만 그리므로 표 바깥 아래선은 없애(마지막 줄 아래선이 대신) 두 줄로 겹치지 않게, 모서리 둥글림 0. 구역 첫 줄 위 진한 선은 없앰(검정 1px 로 통일). + ## 7. 추후 단계 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성. diff --git a/tests/test_project_meeting_cells.py b/tests/test_project_meeting_cells.py index 5562199..e4f4ce0 100644 --- a/tests/test_project_meeting_cells.py +++ b/tests/test_project_meeting_cells.py @@ -177,6 +177,36 @@ class MeetingCellTests(unittest.TestCase): with self.assertRaises(ValueError): self.st.move_meeting_item(item_id=3, direction=-1) + def _order(self): + return [r["id"] for r in sorted(self.conn.rows.values(), key=lambda r: r["sort_order"])] + + def test_drag_move_group_to_position_in_section(self): + """항목 칸 끌어 옮기기(move_meeting_group) — 묶음째로 같은 구역의 묶음 앞/맨 끝, 묶음 사이·다른 구역은 거절.""" + self.assertTrue(self.st.move_meeting_group(item_id=3, before_item_id=1)) + self.assertEqual(self._order(), [3, 1, 2, 4]) + self.assertTrue(self.conn.locked is False and self.conn.writes == 4) + self.assertFalse(self.st.move_meeting_group(item_id=3, before_item_id=3)) # 제자리 + with self.assertRaises(ValueError): + self.st.move_meeting_group(item_id=1, before_item_id=4) # 다른 구역 + with self.assertRaises(KeyError): + self.st.move_meeting_group(item_id=1, before_item_id=99) + + def test_drag_move_keeps_label_group_and_merge_together(self): + for n in range(1, 5): + self.conn.rows[n]["sort_order"] = n + self.conn.rows[2]["label_cont"] = True # 줄1·줄2 = 한 항목 칸 + self.assertTrue(self.st.move_meeting_group(item_id=2, before_item_id=None)) # 이어 붙은 줄을 잡아도 묶음째 + self.assertEqual(self._order(), [3, 1, 2, 4]) + with self.assertRaises(store.GoalCellConflict): + self.st.move_meeting_group(item_id=3, before_item_id=2) # 묶음 사이에는 못 넣음 + self.conn.rows[2]["label_cont"] = False + for n in range(1, 5): + self.conn.rows[n]["sort_order"] = n + self.conn.rows[1]["content_row_span"] = 2 # 주요 업무 칸 1~2 병합 → 같이 움직인다 + self.assertTrue(self.st.move_meeting_group(item_id=3, before_item_id=1)) + self.assertEqual(self._order(), [3, 1, 2, 4]) + self.assertEqual(self.conn.rows[1]["content_row_span"], 2) + def test_plain_and_rich_saves_share_move_lock_and_visible_length_limit(self): rich = store.GOAL_RICH_PREFIX + json.dumps([dict(text="가", bold=True)] * 4000) out = self.st.update_meeting_item(item_id=1, fields={"content": rich})