Merge branch 'feat/project-dnd-perf-unit'

This commit is contained in:
2026-10-19 10:46:13 +09:00
26 changed files with 767 additions and 556 deletions
@@ -2,7 +2,7 @@
{% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %}
@@ -64,7 +64,7 @@
</section>
</div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %}
{% endblock %}
+6
View File
@@ -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`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
+88 -2
View File
@@ -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),
+12
View File
@@ -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})
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -224,4 +224,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
@@ -1,11 +1,19 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- 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) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
{%- endmacro -%}
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
{%- macro adl(lines) -%}
{%- for a in lines or [] -%}<span class="perf-adl" title="{{ (a.label ~ ' ') if a.label }}광고비 {{ '{:,}'.format(a.amount) }}원{% if a.roas is not none %} · ROAS {{ '{:,}'.format(a.roas) }}%{% endif %}">{% if a.label %}<i>{{ a.label }}</i>{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}<em>({{ "{:,}".format(a.roas) }}%)</em>{% endif %}</span>{%- endfor -%}
{%- endmacro -%}
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
@@ -89,7 +97,7 @@
{% for k in kpis %}
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
<div class="perf-kpi-label">{{ k.label }}</div>
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
<div class="perf-kpi-value">{{ money(k.value) }}</div>
<div class="perf-kpi-delta">
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
@@ -107,6 +115,8 @@
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
<span class="perf-head-notes">{% if unit != 'won' %}<span class="perf-muted">단위: {{ unit_label }}</span>{% endif %}
<span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 카페24 는 구글·메타"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
{% if manual_upload_names %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
@@ -138,13 +148,13 @@
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}" tabindex="0"
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}</td>
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% else %}
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
@@ -173,7 +183,7 @@
<!-- ── 월 누적 · 연간 누적 ── -->
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2></div>
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</div>
<div class="erp-table-wrap">
<table class="perf-table">
<thead><tr><th class="perf-th-label">쇼핑몰</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th><th>매출 비중</th></tr></thead>
@@ -204,11 +214,11 @@
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</div>
<div class="perf-year-sum">
<div><span>총매출</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
<div><span>수수료</span><b>₩{{ "{:,}".format(year.total.commission) }}</b></div>
<div><span>수수료 차감 매출</span><b>₩{{ "{:,}".format(year.total.net) }}</b></div>
<div><span>총매출</span><b>{{ money(year.total.gross) }}</b></div>
<div><span>수수료</span><b>{{ money(year.total.commission) }}</b></div>
<div><span>수수료 차감 매출</span><b>{{ money(year.total.net) }}</b></div>
</div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
@@ -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 }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -102,6 +102,25 @@
</p>
</div>
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
<div class="erp-card perf-card" id="perf-view-opts">
<div class="perf-card-head">
<h2 class="perf-h">보기 설정</h2>
<span class="perf-muted">매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
</div>
<div class="perf-opt-row">
<span class="perf-opt-label">매출 단위</span>
<div class="perf-quick" role="radiogroup" aria-label="매출 단위">
{% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %}
<button type="button" class="perf-seg{% if unit == k %} is-active{% endif %}" role="radio"
aria-checked="{{ 'true' if unit == k else 'false' }}" data-unit="{{ k }}">{{ label }}</button>
{% endfor %}
</div>
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
</div>
</div>
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
@@ -183,55 +202,6 @@
<div class="perf-notice" id="perf-backfill-result" hidden></div>
</div>
<div class="erp-card perf-card perf-card-wide">
<div class="perf-card-head"><h2 class="perf-h">쇼핑몰 원본 데이터 확인</h2></div>
<p class="perf-muted">쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음).
쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다.
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.<br>
· <b>쿠팡(윙)</b>: 판매자배송 발주서 + 로켓그로스 주문을 결제일로 모아 날짜별 매출 후보(할인 전·후, 취소분 뺀 값, 로켓그로스 따로)와 판매량 — WING 비즈니스 인사이트 → 판매분석에서 같은 날짜의 "매출(원)"·"판매량"과 비교해 주세요.</p>
<div class="perf-sample-form">
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
<option value="naver">네이버</option>
<option value="elevenst">11번가</option>
<option value="gsshop">GS샵</option>
<option value="toss">토스쇼핑</option>
<option value="coupang">쿠팡(윙)</option>
</select>
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" id="perf-probe-to" value="{{ default_sample_to }}" />
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe">불러오기</button>
</div>
<div id="perf-probe-result"></div>
</div>
<div class="erp-card perf-card perf-card-wide">
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.</p>
<div class="perf-sample-form">
<input class="erp-input perf-date" type="date" id="perf-recon-date" value="{{ default_sample_to }}" />
<button type="button" class="erp-btn erp-btn-outline" id="perf-recon">대조</button>
</div>
<div id="perf-recon-result"></div>
<h3 class="perf-h" style="margin:18px 0 6px">일별 한 번에 비교</h3>
<p class="perf-muted">카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
[API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.</p>
<textarea class="erp-input perf-paste" id="perf-daily-paste" rows="5"
placeholder="2026-09-29(화) 47 116 2,475,300 … 2,477,800 158,000 2,319,800"></textarea>
<div class="perf-sample-form" style="margin-top:6px">
<label class="perf-muted"><input type="checkbox" id="perf-daily-live" /> API 값도 계산(느림)</label>
<button type="button" class="erp-btn erp-btn-outline" id="perf-daily-check">비교</button>
</div>
<div id="perf-daily-result"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
@@ -249,4 +219,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
@@ -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 "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
assert "200,000<em>(300%)</em>" 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 "<i>구글</i>100<em>(413%)</em>" in html
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 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
+3
View File
@@ -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, 바깥 아래선은 마지막 줄 칸 아래선이 대신).
+41
View File
@@ -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)은 그대로 따라간다. 맨 위/맨 아래면 그대로."""
+15
View File
@@ -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 = 묶음 첫 줄. 이어 붙은 줄들이 각자 항목 칸(이름 빈 칸)으로. 줄 순서와 같은 권한."""
@@ -1,7 +1,7 @@
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -298,5 +298,5 @@
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -207,5 +207,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -278,7 +278,8 @@
<li><b>열기</b> — 카드를 누르면 오른쪽에 업무 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 업무는 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 업무는 상태만 표시합니다.</li>
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.</li>
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.
끄는 동안 카드는 살짝 기울어진 모양으로 마우스를 따라오고, 카드 사이를 지나는 순간 <b>점선 자리</b>가 그 사이로 옮겨 가며 다른 카드가 미끄러지듯 비켜납니다 — 놓으면 그 자리에 그대로 들어갑니다(다른 섹션도 같음). 섹션 밖에 놓으면 원래 자리로 돌아갑니다.</li>
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 업무 링크 복사 · 완료로 표시 · 삭제</span></li>
<li><b>댓글</b> — 카드의 <span class="pjh-ui">💬 N</span>을 한 번 누르면 댓글 대화창이 열립니다. (<a href="#comments">16장</a>)</li>
</ul>
@@ -707,6 +708,7 @@
<ul>
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
<li><b>끌어서 순서 바꾸기</b> — <b>항목</b> 칸을 잡고 위아래로 끌면 그 줄(항목 칸으로 묶인 줄·세로 병합 포함)이 마우스를 따라 다른 항목 사이로 바로 옮겨 가고, 놓으면 저장됩니다. 같은 구역 안에서만 움직이며 <kbd>Esc</kbd>는 취소. 살짝 누르기만 하면 예전처럼 이름 수정입니다.</li>
<li><b>주요 업무</b> 칸을 우클릭해 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가</span>를 하면 <b>항목 칸은 그대로</b> 두고 그 항목 안에 줄이 늘어납니다(줄마다 주요 업무·정량 목표는 따로). 같은 메뉴의 <span class="pjh-ui">줄 삭제</span>는 그 한 줄만 지웁니다. 묶인 항목 칸은 항목 칸 메뉴의 <span class="pjh-ui">항목 칸 나누기</span>로 다시 나눕니다. 줄을 추가·삭제하면 새로고침 없이 표가 그 자리에서 움직이며 바뀝니다.</li>
<li><b>구역 순서</b> — 첫 열 <b>구분</b> 칸을 우클릭하거나 마우스를 올려 나오는 <span class="pjh-ui">⋯</span>를 누르면 <span class="pjh-ui">구역 위로 · 구역 아래로 · 구역 끝에 줄 추가</span>가 나옵니다. 구역 안의 줄 순서·병합은 그대로 함께 옮겨지고, 다음에 만드는 회의록도 바뀐 순서를 이어받습니다(회의 완료 전까지, 누구나).</li>
<li>줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -106,5 +106,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -108,5 +108,5 @@
});
})();
</script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -472,5 +472,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project.css?v=20261019a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/project.js?v=20261019a" defer></script>
{% endblock %}
+14
View File
@@ -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; }
+23 -441
View File
@@ -24,6 +24,13 @@
}
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; }
// 매출 단위(실적 설정 "보기 설정", 쿠키 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 = '<p class="perf-muted">카페24에서 불러오는 중…</p>';
try {
const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day));
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; 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) + '건 <span class="perf-muted">' + won(amt) + "</span>" : 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 = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">' + esc(r.date) +
"</th><th>카페24 열(자체몰 채널)</th><th>다른 쇼핑몰 열(외부 마켓)</th>" +
(shopCols ? "<th>합계</th><th>카페24 화면</th><th>차이</th>" : "") + "</tr></thead><tbody>" +
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 = '<td class="perf-num">' + f(both) + '</td><td class="perf-num">' + (c == null ? "" : f(c)) + '</td><td class="perf-num">' +
(c == null ? "" : both === c ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (both > c ? "+" : "") + fmt(both - c) + "</span>") + "</td>";
}
return "<tr" + cls + '><th class="perf-td-label' + (x[3] === "sub" ? " perf-muted" : "") + '">' + esc(x[0]) +
'</th><td class="perf-num">' + f(x[1]) + '</td><td class="perf-num">' + f(x[2]) + "</td>" + cmp + "</tr>";
}).join("") + "</tbody></table>" +
(r.refund_basis
? (function () {
const b = r.refund_basis;
const row = function (label, x, cls) {
return "<tr" + (cls ? ' class="' + cls + '"' : "") + '><th class="perf-td-label">' + label + '</th><td class="perf-num">' +
fmt(x.count) + '</td><td class="perf-num">' + won(x.actual_refund_amount) + '</td><td class="perf-num">' +
won(x.used_points + x.used_credits) + '</td><td class="perf-num">' + won(x.with_points) + "</td></tr>";
};
return '<h4 class="perf-h" style="margin:14px 0 6px">환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">기준</th><th>건수</th><th>실제 환불액</th>' +
"<th>적립금·예치금 환불</th><th>합계(포함)</th></tr></thead><tbody>" +
row("환불완료일 기준 · 완료 <span class='perf-pill is-ok'>적용(합계 포함 칸)</span>", 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("") + "</tbody></table>";
})()
: "") +
((r.refund_candidates || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">환불합계 후보 — 카페24 화면 값을 넣으면 같은 줄을 표시합니다</h4>' +
'<div class="perf-row-inline" style="margin-bottom:6px"><input class="erp-input perf-date" type="text" inputmode="numeric" ' +
'id="perf-recon-target" placeholder="카페24 환불합계" /></div>' +
'<table class="perf-table" id="perf-recon-cands"><thead><tr><th class="perf-th-label">후보</th><th>금액</th><th>차이</th></tr></thead><tbody>' +
r.refund_candidates.map(function (c) {
return '<tr data-amount="' + c.amount + '"><td class="perf-td-label">' + esc(c.label) + '</td><td class="perf-num">' +
won(c.amount) + '</td><td class="perf-num perf-cand-diff">–</td></tr>';
}).join("") + "</tbody></table>"
: "") +
((r.refund_list || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 건별 (환불 API)</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불코드</th><th class="perf-th-label">주문번호</th>' +
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">접수일</th><th class="perf-th-label">완료일</th>' +
"<th>수량</th><th>실제 환불액</th><th>적립금·예치금</th><th class=\"perf-th-label\">환불수단</th></tr></thead><tbody>" +
r.refund_list.map(function (x) {
const st = { T: "환불완료", F: "환불전", M: "환불보류" }[x.status] || x.status;
return '<tr><td class="perf-td-label">' + esc(x.refund_code) + "</td><td>" + esc(x.order_id) + "</td><td>" + esc(x.channel || "–") +
"</td><td>" + esc(st) + "</td><td>" + esc(x.accepted_date || "–") + "</td><td>" + esc(x.refund_date || "–") +
'</td><td class="perf-num">' + fmt(x.quantity) + '</td><td class="perf-num">' + won(x.actual_refund_amount) +
'</td><td class="perf-num">' + won(x.used_points + x.used_credits) + "</td><td>" + esc((x.methods || []).join(", ") || "–") + "</td></tr>";
}).join("") + "</tbody></table>"
: "") +
((r.no_record_claims || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 목록에 없는 네이버페이 취소·반품 (환불합계에 넣은 건 — 주문 전체취소면 배송비 포함)</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">품목</th>' +
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">반영일</th><th class="perf-th-label">상품</th>' +
"<th>수량</th><th>뺀 금액</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">주문 전체취소</th><th>주문 배송비</th></tr></thead><tbody>" +
r.no_record_claims.map(function (c) {
return '<tr><td class="perf-td-label">' + esc(c.order_id) + "</td><td>" + esc(c.item_code) + "</td><td>" + esc(c.place_name || c.market_id || "–") +
"</td><td>" + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + "</td><td>" + esc(c.day) +
"</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) + '</td><td class="perf-num">' + won(c.amount) +
(c.shipping_refund ? ' <span class="perf-muted">(배송비 ' + fmt(c.shipping_refund) + ")</span>" : "") +
'</td><td class="perf-num">' + won(c.item_payment_amount) + '</td><td class="perf-num">' + won(c.coupon) + "</td><td>" +
(c.order_all_claimed ? "<b>예</b>" : "아니오") + '</td><td class="perf-num">' + won(c.order_shipping_fee) + "</td></tr>";
}).join("") + "</tbody></table>"
: "") +
((r.reduced_orders || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 결제한 주문 중 금액이 줄어든 주문 (취소·반품) — "환불 기록 없음"이 환불 API 에 안 잡힌 건</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th>' +
'<th class="perf-th-label">결제수단</th><th class="perf-th-label">품목 상태</th><th class="perf-th-label">취소·환불일</th>' +
"<th>결제 당시</th><th>현재</th><th>줄어든 금액</th><th>환불 기록</th></tr></thead><tbody>" +
r.reduced_orders.map(function (x) {
const miss = x.diff - x.refunded;
return "<tr" + (miss > 0 ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(x.order_id) + "</td><td>" +
esc(x.channel || "–") + "</td><td>" + esc(x.payment || "–") + "</td><td>" +
esc(x.statuses.join(", ") + (x.naver_pay.length ? " / 네이버페이 " + x.naver_pay.join(",") : "")) + "</td><td>" +
esc(x.claim_dates.join(", ") || "–") + '</td><td class="perf-num">' + won(x.initial) + '</td><td class="perf-num">' +
won(x.now) + '</td><td class="perf-num">' + won(x.diff) + '</td><td class="perf-num">' +
(x.refunded ? won(x.refunded) + ' <span class="perf-muted">' + esc(x.refund_dates.join(", ")) + "</span>" : "<b>없음</b>") + "</td></tr>";
}).join("") + "</tbody></table>"
: "") +
(r.claims
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 취소·반품·교환 완료 품목 (주문 API)</h4>' +
((r.claims.errors || []).length ? '<p class="perf-notice is-warn">' + esc(r.claims.errors.join(" / ")) + "</p>" : "") +
((r.claims.items || []).length
? '<table class="perf-table"><thead><tr><th class="perf-th-label">조회</th><th class="perf-th-label">주문번호</th>' +
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">클레임</th><th class="perf-th-label">상품</th>' +
"<th>수량</th><th>판매가×수량</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">환불 기록</th></tr></thead><tbody>" +
r.claims.items.map(function (c) {
return "<tr" + (c.done ? "" : ' class="perf-muted"') + '><td class="perf-td-label">' + esc(c.via) + "</td><td>" + esc(c.order_id) +
"</td><td>" + esc(c.channel || "–") + "</td><td>" + esc(c.status + (c.status_text ? " " + c.status_text : "")) +
"</td><td>" + esc(c.claim_code || "–") + "</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) +
'</td><td class="perf-num">' + won(c.product_amount) + '</td><td class="perf-num">' + won(c.payment_amount) +
'</td><td class="perf-num">' + won(c.coupon) + "</td><td>" + (c.has_refund ? "있음" : '<b>없음</b>') + "</td></tr>";
}).join("") + "</tbody></table>" +
'<p class="perf-foot perf-muted">전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) +
'. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).</p>'
: '<p class="perf-muted">없음</p>')
: "") +
((r.by_channel || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">주문 채널별</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">market_id</th><th class="perf-th-label">주문경로</th>' +
'<th class="perf-th-label">구분</th><th class="perf-th-label">반영 열</th><th>주문수</th><th>결제합계</th>' +
"<th>PC 주문</th><th>모바일 주문</th><th>환불</th><th>순매출</th></tr></thead><tbody>" +
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" ? "외부 마켓" : '<span class="perf-err" style="display:inline">알 수 없는 채널</span>';
return '<tr><td class="perf-td-label">' + esc(b.market_id) + "</td><td>" + esc(b.place || "–") +
(b.place_id && b.place_id !== b.place ? ' <span class="perf-muted">' + esc(b.place_id) + "</span>" : "") +
"</td><td>" + (b.kind === "unknown" ? kind : esc(kind)) + "</td><td>" + esc(col) +
'</td><td class="perf-num">' + fmt(b.orders) + '</td><td class="perf-num">' + won(b.total) +
'</td><td class="perf-num">' + dev(b.pc_orders, b.pc_total) + '</td><td class="perf-num">' + dev(b.mobile_orders, b.mobile_total) +
'</td><td class="perf-num">' + won(-b.refund_amount) + '</td><td class="perf-num">' + won(b.total - b.refund_amount) + "</td></tr>";
}).join("") + "</tbody>" +
// 카페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 '<tfoot><tr class="perf-row-week"><th class="perf-td-label" colspan="4">카페24 열(자체몰) 합계</th><td class="perf-num">' +
fmt(t.o) + '</td><td class="perf-num">' + won(t.t) + '</td><td class="perf-num">' + dev(t.po, t.pt) +
'</td><td class="perf-num">' + dev(t.mo, t.mt) + '</td><td class="perf-num">' + won(-t.ra) +
'</td><td class="perf-num">' + won(t.t - t.ra) + "</td></tr></tfoot>";
})() + "</table>" +
'<p class="perf-foot perf-muted">한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' +
'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.</p>'
: "") +
((r.by_payment || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">결제수단별 (카페24 열)</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">결제수단</th><th>주문수</th><th>결제합계</th><th>비중</th></tr></thead><tbody>' +
(function () {
const tot = r.by_payment.reduce(function (a, p) { return a + p.total; }, 0);
return r.by_payment.map(function (p) {
return '<tr><td class="perf-td-label">' + esc(p.method) + '</td><td class="perf-num">' + fmt(p.orders) +
'</td><td class="perf-num">' + won(p.total) + '</td><td class="perf-num">' +
(tot > 0 ? (p.total / tot * 100).toFixed(1) + "%" : "–") + "</td></tr>";
}).join("");
})() + "</tbody></table>"
: "") +
(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 '<div><h5 class="perf-h" style="margin:6px 0">' + esc(PART[p]) + "</h5>" +
(keys.length ? '<table class="perf-table"><tbody>' + keys.map(function (k) {
return "<tr" + (gap && f[k] === gap ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(k) +
'</td><td class="perf-num">' + fmt(f[k]) + "</td></tr>";
}).join("") + "</tbody></table>" : '<p class="perf-muted">0 아닌 값 없음</p>') + "</div>";
}).join("");
const odd = (r.odd_orders || []).map(function (o) {
return '<tr><td class="perf-td-label">' + esc(o.order_id) + "</td><td>" + esc(o.channel || "–") + '</td><td class="perf-num">' +
fmt(o.items_gross) + '</td><td class="perf-num">' + fmt(o.order_price_amount) + '</td><td class="perf-num">' + fmt(o.total) +
'</td><td style="white-space:normal;font-size:11.5px">' + 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("<br>") + "</td></tr>";
}).join("");
return '<h4 class="perf-h" style="margin:14px 0 6px">원본 금액 필드 합계 (진단 — 그날 결제 주문 전체)' +
(gap ? ' · 판매가 합계 − 카페24 상품구매금액 = <b>' + fmt(gap) + "</b> (같은 값 강조)" : "") + "</h4>" +
'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:10px">' + cells + "</div>" +
(odd ? '<h4 class="perf-h" style="margin:14px 0 6px">상품금액이 100원 단위가 아니거나 판매가×수량 합과 다른 주문</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th><th>판매가×수량</th>' +
'<th>주문 상품금액</th><th>결제합계(계산)</th><th class="perf-th-label">품목 금액 필드(0 제외)</th></tr></thead><tbody>' + odd + "</tbody></table>" : "");
})()
: "") +
'<p class="perf-foot perf-muted">' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) +
"건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.</p>";
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 = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} 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 = '<p class="perf-notice is-warn">날짜가 있는 줄을 찾지 못했습니다. 카페24 일별 매출내역 표를 복사해 붙여 넣으세요.</p>'; return; }
const live = document.getElementById("perf-daily-live").checked;
dailyBtn.disabled = true;
out.innerHTML = '<p class="perf-muted">' + (live ? "저장값과 카페24 API 값을 계산하는 중… (기간이 길면 1~2분)" : "저장값을 불러오는 중…") + "</p>";
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 = '<p class="perf-notice is-warn">' + esc(r.message) + "</p>"; 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 ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (d > 0 ? "+" : "") + fmt(d) + "</span>";
};
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 = '<span class="perf-pill is-ok">일치</span>';
else if (l && liveOk) { verdict = '<span class="perf-pill">다시 가져오면 해결</span>'; stale++; }
else if (l) {
const what = [l.paid !== c.paid ? "결제" : "", l.refund !== c.refund ? "환불" : ""].filter(Boolean).join("·");
verdict = '<span class="perf-pill is-bad">규칙 차이(' + what + ")</span>"; rule++;
} else verdict = '<span class="perf-pill is-bad">차이</span>';
if (!dbOk) bad++;
const wd = "일월화수목금토"[new Date(d + "T00:00:00").getDay()];
return "<tr" + (dbOk ? "" : ' class="perf-row-diff"') + '><td class="perf-td-label"><button type="button" class="perf-link" data-recon-day="' + d + '">' +
esc(d) + "(" + wd + ")</button>" + (d === todayIso ? ' <span class="perf-muted">오늘·집계 중</span>' : "") + "</td>" +
'<td class="perf-num">' + (c.orders == null ? "–" : fmt(c.orders)) + ' <span class="perf-muted">/ ' + fmt(x.orders) + (l ? " / " + fmt(l.orders) : "") + "</span></td>" +
'<td class="perf-num">' + won(c.paid) + '</td><td class="perf-num">' + diff(x.paid, c.paid) + "</td>" + (l ? '<td class="perf-num">' + diff(l.paid, c.paid) + "</td>" : "") +
'<td class="perf-num">' + won(c.refund) + '</td><td class="perf-num">' + diff(x.refund, c.refund) + "</td>" + (l ? '<td class="perf-num">' + diff(l.refund, c.refund) + "</td>" : "") +
"<td>" + verdict + (x.synced_at ? '<div class="perf-muted" style="font-size:11px">저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "</div>" : "") + "</td></tr>";
}).join("");
const head = '<tr><th class="perf-th-label">날짜</th><th>주문수 <span class="perf-muted">카페24 / 저장' + (lv ? " / API" : "") + "</span></th>" +
"<th>결제합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") +
"<th>환불합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") + '<th class="perf-th-label">판정</th></tr>';
const foot = '<tr class="perf-row-week"><th class="perf-td-label">합계</th><td></td><td class="perf-num">' + won(sum.cp) + '</td><td class="perf-num">' +
diff(sum.dp, sum.cp) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lp, sum.cp) + "</td>" : "") + '<td class="perf-num">' + won(sum.cr) +
'</td><td class="perf-num">' + diff(sum.dr, sum.cr) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lr, sum.cr) + "</td>" : "") + "<td></td></tr>";
const summary = bad
? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다")
: "모든 날짜가 일치합니다.";
out.innerHTML = '<p class="perf-notice ' + (bad ? "is-warn" : "is-ok") + '" style="margin-top:8px">' + esc(summary) +
(r.live_error ? "<br>API 계산 실패: " + esc(r.live_error) : "") + "</p>" +
(stale ? '<div class="perf-sample-form"><button type="button" class="erp-btn erp-btn-primary" id="perf-daily-resync" data-from="' + from +
'" data-to="' + to + '">' + esc(from + " ~ " + to) + " 카페24 다시 가져오기</button></div>" : "") +
'<table class="perf-table" style="margin-top:8px"><thead>' + head + "</thead><tbody>" + body + "</tbody><tfoot>" + foot + "</tfoot></table>" +
'<p class="perf-foot perf-muted">차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.</p>';
} catch (err) {
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} 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 = '<p class="perf-muted">' + loading + "</p>";
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 = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; 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 ? '<p class="perf-notice' + (cut ? " is-warn" : "") + '" style="margin-top:8px">조회 기간 <b>' + esc(shown) + "</b>" +
(cut ? " — 원본 데이터 확인은 한 번에 31일까지라 " + esc(r.to) + " 뒤(~" + esc(to) + ")는 조회하지 않았습니다. " +
"1년치 매출은 위 [과거 매출 가져오기]로 받으세요(31일씩 나눠 불러 저장)." : "") + "</p>" : "";
const summary = range + '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
'<th class="perf-th-label">주소</th><th class="perf-th-label">결과</th><th>건수</th></tr></thead><tbody>' +
r.probes.map(function (p) {
return '<tr><td class="perf-td-label">' + esc(p.label) + '</td><td class="perf-muted">' + esc(p.path) + "</td><td>" +
(p.ok ? '<span class="perf-pill is-ok">동작</span>' : '<span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(p.error) + "</span>") +
'</td><td class="perf-num">' + (p.ok ? fmt(p.count) : "") + "</td></tr>";
}).join("") + "</tbody></table>";
const details = r.probes.filter(function (p) { return p.ok && p.count; }).map(function (p) {
return '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(p.label) + " — " + fmt(p.count) + "줄</h4>" +
'<table class="perf-table"><thead><tr><th class="perf-th-label">항목</th><th>채워진 줄</th><th>숫자 합계</th>' +
'<th class="perf-th-label">예시 값</th></tr></thead><tbody>' +
p.fields.map(function (f) {
return '<tr><td class="perf-td-label">' + esc(f.name) + '</td><td class="perf-num">' + fmt(f.filled) + '</td><td class="perf-num">' +
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
}).join("") + "</tbody></table>";
}).join("");
// 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>' +
esc((r.day_cols || {}).amount || "매출") + "</th>" +
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
r.days.map(function (d) {
return '<tr><td class="perf-td-label">' + esc(d.date) + '</td><td class="perf-num">' + fmt(d.orders) +
'</td><td class="perf-num">' + fmt(d.amount) + '</td><td class="perf-num">' + fmt(d.claimed || 0) +
'</td><td class="perf-num">' + fmt(d.ship || 0) + "</td></tr>";
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' +
["orders", "amount", "claimed", "ship"].map(function (k) {
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
}).join("") + "</tr></tbody></table>" : "";
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
const rc = r.refund_candidates || [];
const candDays = (r.days || []).map(function (d) { return d.date; });
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(r.candidates_title || "환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불") + "</h4>" +
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th>' +
rc.map(function (c) { return "<th>" + esc(c.label) + "</th>"; }).join("") + "</tr></thead><tbody>" +
candDays.map(function (dt) {
return '<tr><td class="perf-td-label">' + esc(dt) + "</td>" + rc.map(function (c) {
return '<td class="perf-num">' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "</td>";
}).join("") + "</tr>";
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' + rc.map(function (c) {
if (c.error) return '<td><span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(c.error) + "</span></td>";
const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0);
return '<td class="perf-num"><b>' + fmt(t) + "</b></td>";
}).join("") + "</tr></tbody></table>" +
rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) {
return '<p class="perf-muted" style="margin:10px 0 4px">' + esc(c.label) + " — " + fmt(c.rows.length) + "건</p>" +
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불일</th><th class="perf-th-label">주문일</th>' +
'<th class="perf-th-label">주문번호</th>' +
'<th class="perf-th-label">주문상품</th><th>금액</th><th class="perf-th-label">메모</th></tr></thead><tbody>' +
c.rows.map(function (x) {
return '<tr><td class="perf-td-label">' + esc(x.date) + "</td><td>" + esc(x.orderDate || "") + "</td><td>" +
esc(x.orderId) + "</td><td>" + esc(x.orderProductId) +
'</td><td class="perf-num">' + fmt(x.amount) + '</td><td class="perf-muted">' + esc(x.note) + "</td></tr>";
}).join("") + "</tbody></table>";
}).join("") : "";
out.innerHTML = summary + days + cands + (details ||'<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
} catch (err) {
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} finally { probe.disabled = false; }
});
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
const backfill = document.getElementById("perf-backfill");
if (backfill) backfill.addEventListener("click", async function () {
+22 -4
View File
@@ -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 {
+287 -26
View File
@@ -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), 새 줄은 위에서 내려오며 잠깐 강조. 동작 줄이기 설정이면 애니메이션 없이.
+12
View File
@@ -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=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널,
+18
View File
@@ -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. 추후 단계
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
+30
View File
@@ -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})