diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html index 7e2ad3e..14f4544 100644 --- a/app/modules/notice/templates/notice/admin.html +++ b/app/modules/notice/templates/notice/admin.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index a0e7d64..9b3bbe0 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -33,6 +33,12 @@ - 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003). - 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). +## 매출 실적 화면 (2026-10-19) + +- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음. +- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. +- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김). + ## 광고비 (`/performance/ads`) - 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 7abbed6..d736cf6 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -6,7 +6,7 @@ HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권 from __future__ import annotations from datetime import date, timedelta -from decimal import Decimal +from decimal import ROUND_HALF_UP, Decimal from typing import Any, Mapping, Sequence from . import calc @@ -32,6 +32,90 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] return (status_row or {}).get("status") or "unknown" +# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름) +UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")} +UNIT_COOKIE = "perf_unit" + + +def normalize_unit(value: Any) -> str: + return value if value in UNITS else "won" + + +def amount_text(value: Any, unit: str = "won") -> str: + """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림).""" + div, places, _ = UNITS[normalize_unit(unit)] + if div == 1: + return f"{int(value):,}" + q = (Decimal(int(value)) / div).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP) + return f"{q:,.{places}f}" + + +def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any], + period: Any, q_start: date, q_end: date) -> None: + """매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS). + 카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). + 광고비 표(005)가 없거나 읽기 실패면 줄 없음.""" + from . import ad_spend # noqa: WPS433 + + by_code = sales_ad_channels() + want = {ch for c in codes for ch, _ in by_code.get(c, ())} + for r in table: + r["ads"], r["ads_total"] = {}, None + if not want: + return + try: + amounts, _ = store.ad_amounts(q_start, q_end) + reader = getattr(store, "ad_roas", None) + roas_map = reader(q_start, q_end) if reader else {} + except Exception: # noqa: BLE001 — 광고비 표가 없어도 매출 화면은 그대로 + return + spend_by: dict[str, list[tuple[date, int]]] = {} + for (d, ch), v in amounts.items(): + if ch in want and v: + spend_by.setdefault(ch, []).append((d, int(v))) + + sales_by: dict[str, list[tuple[date, int]]] = {} + for (d, c), m in cells.items(): + sales_by.setdefault(c, []).append((d, int(m.gross))) + + def spend(ch: str, s: date, e: date) -> int: + return sum(v for d, v in spend_by.get(ch, ()) if s <= d <= e) + + def sales(c: str, s: date, e: date) -> int: + return sum(v for d, v in sales_by.get(c, ()) if s <= d <= e) + + for r in table: + s = date.fromisoformat(r["from"]) if r.get("from") else period.start + e = date.fromisoformat(r["to"]) if r.get("to") else period.end + tot_spend = tot_sales = 0 + for c in codes: + lines = [] + for ch, label in by_code.get(c, ()): + amt = spend(ch, s, e) + if not amt: + continue + rs = ad_spend.channel_roas(ch, lambda m: sales(m, s, e), amt, + lambda f: ad_spend.file_roas(f, roas_map, amounts, s, e)) + lines.append({"label": label, "amount": amt, "roas": rs}) + tot_spend += amt + if lines: + r["ads"][c] = lines + tot_sales += sales(c, s, e) + if tot_spend: + r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, tot_spend)} + + +def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]: + """쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고, + 나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출).""" + from . import ad_spend # noqa: WPS433 + + out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)} + for ch, c in ad_spend.ROAS_SALES_CODE.items(): + out[c] = out.get(c, ()) + ((ch, ""),) + return out + + def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None, custom_to: date | None = None, selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None, @@ -105,6 +189,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "error": (statuses.get(m["code"]) or {}).get("last_error", "")}) m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes) + table = calc.main_table(period, codes, cells, today=today, holidays=holidays) + _ad_lines(store, table, codes, cells, period, q_start, q_end) def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str: if kind == "custom": @@ -144,7 +230,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "short_names": short, "selected_all": len(codes) == len(all_codes), "kpis": kpis, - "table": calc.main_table(period, codes, cells, today=today, holidays=holidays), + "table": table, "month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells), "year": calc.year_months(year_period.start.year, codes, cells, today=today), "chart_daily": calc.daily_series(period, codes, cells), diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 9b617de..0f379b9 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -135,9 +135,20 @@ def dashboard_page( holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())), ) ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross" + _unit_ctx(request, ctx) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) +def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None: + """매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다.""" + from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433 + + unit = normalize_unit(request.cookies.get(UNIT_COOKIE)) + ctx["unit"] = unit + ctx["unit_label"] = UNITS[unit][2] + ctx["amt"] = lambda v: amount_text(v, unit) + + @router.get("/ads", response_class=HTMLResponse) def ads_page( request: Request, @@ -192,6 +203,7 @@ def settings_page(request: Request): ) ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured()) ctx["ad_api_ready"] = store.ad_api_ready() + _unit_ctx(request, ctx) return render_template(request, "performance/settings.html", {**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx}) diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index ac7085b..e2ac119 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -224,4 +224,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 8d081d7..c3959ac 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,11 +1,19 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} {%- elif v == 0 -%}– - {%- else -%}{{ "{:,}".format(v) }}{%- endif -%} + {%- else -%}{{ amt(v) }}{%- endif -%} +{%- endmacro -%} +{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#} +{%- macro money(v) -%} + {%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}{{ unit_label }}{%- endif -%} +{%- endmacro -%} +{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#} +{%- macro adl(lines) -%} + {%- for a in lines or [] -%}{% if a.label %}{{ a.label }}{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}({{ "{:,}".format(a.roas) }}%){% endif %}{%- endfor -%} {%- endmacro -%} {#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#} @@ -89,7 +97,7 @@ {% for k in kpis %}
| 쇼핑몰 | 총매출 | 수수료 | 수수료 차감 매출 | 매출 비중 | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
카페24에서 불러오는 중…
'; - try { - const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day)); - if (!r.ok) { out.innerHTML = '' + esc((r.label ? r.label + " — " : "") + r.message) + "
"; return; } - const s = r.orders.self, m = r.orders.market, rs = r.refunds.self, rm = r.refunds.market; - const dev = function (n, amt) { return n ? fmt(n) + '건 ' + won(amt) + "" : won(0); }; - const MARKET_NAMES = {}; - root.querySelectorAll("tr[data-code]").forEach(function (tr) { MARKET_NAMES[tr.dataset.code] = tr.dataset.name; }); - const disc = ["membership_discount_amount", "set_product_discount_amount", "app_discount_amount", - "market_other_discount_amount", "shipping_fee_discount_amount"]; - const coup = ["coupon_discount_price", "coupon_shipping_fee_amount"]; - const LABEL = { - membership_discount_amount: "회원할인", set_product_discount_amount: "세트상품할인", app_discount_amount: "앱할인", - market_other_discount_amount: "마켓 기타할인", shipping_fee_discount_amount: "배송비할인", - coupon_discount_price: "상품쿠폰", coupon_shipping_fee_amount: "배송비쿠폰", - }; - const sum = function (g, keys) { return keys.reduce(function (a, k) { return a + (g[k] || 0); }, 0); }; - // x[4] = 붙여넣은 카페24 일별 매출내역 열 번호(일별 비교에서 이 날짜를 눌렀을 때 차이 표시) - const rows = [ - ["주문수", s.orders, m.orders, "cnt", 0], ["품목수(수량 합계)", s.items, m.items, "cnt", 1], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt", 1], - ["상품구매금액", s.order_price_amount, m.order_price_amount, "", 2], - ["배송비", s.shipping_fee, m.shipping_fee, "", 3], - ["할인 합계", sum(s, disc), sum(m, disc), "", 4], - ].concat(disc.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; })) - .concat([["쿠폰 합계", sum(s, coup), sum(m, coup), "", 5]]) - .concat(coup.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; })) - .concat([ - [" 참고식: 상품구매금액 + 배송비 − 할인 − 쿠폰", s.goods_total, m.goods_total, "sub"], - ["실결제금액", s.payment_amount, m.payment_amount, "", 6], - ["적립금 사용", s.points_spent_amount, m.points_spent_amount, "", 7], - ["예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "", 8], - ["네이버포인트", s.naver_point, m.naver_point, "", 9], - ["결제합계(실결제 + 적립금 + 예치금 + 네이버포인트)", s.total, m.total, "key", 10], - ["환불 건수(환불 목록)", rs.count, rm.count, "cnt"], - [" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"], - [" · 적립금 환불", rs.used_points, rm.used_points, "sub"], - [" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"], - ["환불 목록 없는 네이버페이 취소·반품 품목 수", rs.no_record_count, rm.no_record_count, "cnt"], - [" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"], - ["환불합계", rs.total, rm.total, "key", 11], - ["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12], - ]); - const shopCols = (lastShop[r.date] || {}).cols || null; - out.innerHTML = '| ' + esc(r.date) + - " | 카페24 열(자체몰 채널) | 다른 쇼핑몰 열(외부 마켓) | " + - (shopCols ? "합계 | 카페24 화면 | 차이 | " : "") + "' + f(both) + ' | ' + (c == null ? "" : f(c)) + ' | ' + - (c == null ? "" : both === c ? '✓' : '' + (both > c ? "+" : "") + fmt(both - c) + "") + " | "; - } - return "
|---|---|---|---|---|---|
| ' + esc(x[0]) + - ' | ' + f(x[1]) + ' | ' + f(x[2]) + " | " + cmp + "
| 기준 | 건수 | 실제 환불액 | ' + - "적립금·예치금 환불 | 합계(포함) |
|---|
| 후보 | 금액 | 차이 |
|---|---|---|
| ' + esc(c.label) + ' | ' + - won(c.amount) + ' | – |
| 환불코드 | 주문번호 | ' + - '채널 | 상태 | 접수일 | 완료일 | ' + - "수량 | 실제 환불액 | 적립금·예치금 | 환불수단 |
|---|---|---|---|---|---|---|---|---|---|
| ' + esc(x.refund_code) + " | " + esc(x.order_id) + " | " + esc(x.channel || "–") + - " | " + esc(st) + " | " + esc(x.accepted_date || "–") + " | " + esc(x.refund_date || "–") + - ' | ' + fmt(x.quantity) + ' | ' + won(x.actual_refund_amount) + - ' | ' + won(x.used_points + x.used_credits) + " | " + esc((x.methods || []).join(", ") || "–") + " |
| 주문번호 | 품목 | ' + - '채널 | 상태 | 반영일 | 상품 | ' + - "수량 | 뺀 금액 | 품목 결제금액 | 쿠폰 | 주문 전체취소 | 주문 배송비 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| ' + esc(c.order_id) + " | " + esc(c.item_code) + " | " + esc(c.place_name || c.market_id || "–") + - " | " + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + " | " + esc(c.day) + - " | " + esc(c.product_name) + ' | ' + fmt(c.quantity) + ' | ' + won(c.amount) + - (c.shipping_refund ? ' (배송비 ' + fmt(c.shipping_refund) + ")" : "") + - ' | ' + won(c.item_payment_amount) + ' | ' + won(c.coupon) + " | " + - (c.order_all_claimed ? "예" : "아니오") + ' | ' + won(c.order_shipping_fee) + " |
| 주문번호 | 채널 | ' + - '결제수단 | 품목 상태 | 취소·환불일 | ' + - "결제 당시 | 현재 | 줄어든 금액 | 환불 기록 |
|---|---|---|---|---|---|---|---|---|
| ' + esc(x.order_id) + " | " + - esc(x.channel || "–") + " | " + esc(x.payment || "–") + " | " + - esc(x.statuses.join(", ") + (x.naver_pay.length ? " / 네이버페이 " + x.naver_pay.join(",") : "")) + " | " + - esc(x.claim_dates.join(", ") || "–") + ' | ' + won(x.initial) + ' | ' + - won(x.now) + ' | ' + won(x.diff) + ' | ' + - (x.refunded ? won(x.refunded) + ' ' + esc(x.refund_dates.join(", ")) + "" : "없음") + " |
' + esc(r.claims.errors.join(" / ")) + "
" : "") + - ((r.claims.items || []).length - ? '| 조회 | 주문번호 | ' + - '채널 | 상태 | 클레임 | 상품 | ' + - "수량 | 판매가×수량 | 품목 결제금액 | 쿠폰 | 환불 기록 |
|---|---|---|---|---|---|---|---|---|---|---|
| ' + esc(c.via) + " | " + esc(c.order_id) + - " | " + esc(c.channel || "–") + " | " + esc(c.status + (c.status_text ? " " + c.status_text : "")) + - " | " + esc(c.claim_code || "–") + " | " + esc(c.product_name) + ' | ' + fmt(c.quantity) + - ' | ' + won(c.product_amount) + ' | ' + won(c.payment_amount) + - ' | ' + won(c.coupon) + " | " + (c.has_refund ? "있음" : '없음') + " |
전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) + - '. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).
' - : '없음
') - : "") + - ((r.by_channel || []).length - ? '| market_id | 주문경로 | ' + - '구분 | 반영 열 | 주문수 | 결제합계 | ' + - "PC 주문 | 모바일 주문 | 환불 | 순매출 |
|---|---|---|---|---|---|---|---|---|---|
| ' + esc(b.market_id) + " | " + esc(b.place || "–") + - (b.place_id && b.place_id !== b.place ? ' ' + esc(b.place_id) + "" : "") + - " | " + (b.kind === "unknown" ? kind : esc(kind)) + " | " + esc(col) + - ' | ' + fmt(b.orders) + ' | ' + won(b.total) + - ' | ' + dev(b.pc_orders, b.pc_total) + ' | ' + dev(b.mobile_orders, b.mobile_total) + - ' | ' + won(-b.refund_amount) + ' | ' + won(b.total - b.refund_amount) + " |
| 카페24 열(자체몰) 합계 | ' + - fmt(t.o) + ' | ' + won(t.t) + ' | ' + dev(t.po, t.pt) + - ' | ' + dev(t.mo, t.mt) + ' | ' + won(-t.ra) + - ' | ' + won(t.t - t.ra) + " | |||
한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' + - 'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.
' - : "") + - ((r.by_payment || []).length - ? '| 결제수단 | 주문수 | 결제합계 | 비중 |
|---|---|---|---|
| ' + esc(p.method) + ' | ' + fmt(p.orders) + - ' | ' + won(p.total) + ' | ' + - (tot > 0 ? (p.total / tot * 100).toFixed(1) + "%" : "–") + " |
| ' + esc(k) + - ' | ' + fmt(f[k]) + " |
0 아닌 값 없음
') + "| 주문번호 | 채널 | 판매가×수량 | ' + - '주문 상품금액 | 결제합계(계산) | 품목 금액 필드(0 제외) |
|---|
' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) + - "건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.
"; - const target = document.getElementById("perf-recon-target"); - if (target) target.addEventListener("input", function () { - const v = parseInt(target.value.replace(/[^0-9-]/g, ""), 10); - out.querySelectorAll("#perf-recon-cands tr[data-amount]").forEach(function (tr) { - const a = parseInt(tr.dataset.amount, 10); - const d = tr.querySelector(".perf-cand-diff"); - if (isNaN(v)) { d.textContent = "–"; tr.classList.remove("perf-row-match"); return; } - d.textContent = a === v ? "일치" : fmt(a - v); - tr.classList.toggle("perf-row-match", a === v); - }); - }); - } catch (err) { - out.innerHTML = '' + esc(err.message) + "
"; - } finally { recon.disabled = false; } - }); - - // ── 일별 한 번에 비교 — 카페24 일별 매출내역 붙여넣기 ↔ 저장값 ↔ 지금 API 값 ── - // 붙여넣은 한 줄: "2026-09-29(화) 주문수 품목수 … 결제합계 환불합계 순매출" — 뒤의 세 숫자와 첫 숫자(주문수)만 쓴다. - function parseDaily(text) { - const out = {}; - String(text || "").split(/\r?\n/).forEach(function (line) { - const m = line.match(/(\d{4})[-./](\d{2})[-./](\d{2})/); - if (!m) return; - const nums = (line.slice(m.index + m[0].length).match(/-?\d[\d,]*/g) || []) - .map(function (x) { return parseInt(x.replace(/,/g, ""), 10); }); - if (nums.length < 3) return; - const n = nums.length; - out[m[1] + "-" + m[2] + "-" + m[3]] = { orders: n >= 13 ? nums[0] : null, paid: nums[n - 3], refund: nums[n - 2], net: nums[n - 1], - cols: n >= 13 ? nums.slice(n - 13) : null }; - }); - return out; - } - const dailyBtn = document.getElementById("perf-daily-check"); - if (dailyBtn) dailyBtn.addEventListener("click", async function () { - const out = document.getElementById("perf-daily-result"); - const shop = lastShop = parseDaily(document.getElementById("perf-daily-paste").value); - const dates = Object.keys(shop).sort(); - if (!dates.length) { out.innerHTML = '날짜가 있는 줄을 찾지 못했습니다. 카페24 일별 매출내역 표를 복사해 붙여 넣으세요.
'; return; } - const live = document.getElementById("perf-daily-live").checked; - dailyBtn.disabled = true; - out.innerHTML = '' + (live ? "저장값과 카페24 API 값을 계산하는 중… (기간이 길면 1~2분)" : "저장값을 불러오는 중…") + "
"; - try { - const from = dates[0], to = dates[dates.length - 1]; - const r = await api("GET", "/performance/api/marketplaces/cafe24/daily-check?from=" + from + "&to=" + to + (live ? "&live=1" : "")); - if (!r.ok) { out.innerHTML = '' + esc(r.message) + "
"; return; } - const byDate = function (rows) { const o = {}; (rows || []).forEach(function (x) { o[x.date] = x; }); return o; }; - const db = byDate(r.db), lv = r.live ? byDate(r.live) : null; - const zero = { paid: 0, refund: 0, orders: 0 }; - const diff = function (ours, theirs) { - const d = ours - theirs; - return d === 0 ? '✓' : '' + (d > 0 ? "+" : "") + fmt(d) + ""; - }; - const todayIso = today(); - let bad = 0, stale = 0, rule = 0; - const sum = { cp: 0, cr: 0, dp: 0, dr: 0, lp: 0, lr: 0 }; - const body = dates.slice().reverse().map(function (d) { - const c = shop[d], x = db[d] || zero, l = lv ? (lv[d] || zero) : null; - sum.cp += c.paid; sum.cr += c.refund; sum.dp += x.paid; sum.dr += x.refund; - if (l) { sum.lp += l.paid; sum.lr += l.refund; } - const dbOk = x.paid === c.paid && x.refund === c.refund; - const liveOk = l && l.paid === c.paid && l.refund === c.refund; - let verdict; - if (dbOk) verdict = '일치'; - else if (l && liveOk) { verdict = '다시 가져오면 해결'; stale++; } - else if (l) { - const what = [l.paid !== c.paid ? "결제" : "", l.refund !== c.refund ? "환불" : ""].filter(Boolean).join("·"); - verdict = '규칙 차이(' + what + ")"; rule++; - } else verdict = '차이'; - if (!dbOk) bad++; - const wd = "일월화수목금토"[new Date(d + "T00:00:00").getDay()]; - return "' + esc(summary) +
- (r.live_error ? "
API 계산 실패: " + esc(r.live_error) : "") + "
차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.
'; - } catch (err) { - out.innerHTML = '' + esc(err.message) + "
"; - } finally { dailyBtn.disabled = false; } - }); - const dailyOut = document.getElementById("perf-daily-result"); - if (dailyOut) dailyOut.addEventListener("click", async function (e) { - const dayBtn = e.target.closest("[data-recon-day]"); - if (dayBtn && recon) { - document.getElementById("perf-recon-date").value = dayBtn.dataset.reconDay; - recon.click(); - recon.scrollIntoView({ behavior: "smooth", block: "center" }); - return; - } - const rs = e.target.closest("#perf-daily-resync"); - if (!rs) return; - if (!(await confirmMsg(rs.dataset.from + " ~ " + rs.dataset.to + " 카페24 매출을 지금 규칙으로 다시 가져옵니다."))) return; - rs.disabled = true; - rs.textContent = "가져오는 중…"; - try { - const res = await api("POST", "/performance/api/sync", { from: rs.dataset.from, to: rs.dataset.to, codes: ["cafe24"] }); - const r0 = (res.results || [])[0]; - if (r0 && !r0.ok) throw new Error((r0.label || r0.status) + ": " + (r0.message || "")); - dailyBtn.click(); - } catch (err) { - alertMsg("다시 가져오기 실패: " + err.message); - rs.disabled = false; - } - }); - - // ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑·쿠팡) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ── - const probe = document.getElementById("perf-probe"); - if (probe) probe.addEventListener("click", async function () { - const day = document.getElementById("perf-probe-date").value; - const out = document.getElementById("perf-probe-result"); - if (!day) return; - probe.disabled = true; - const codeSel = document.getElementById("perf-probe-code"); - const code = codeSel ? codeSel.value : "elevenst"; - const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)", - gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)", - coupang: "쿠팡에서 불러오는 중… (판매자배송 상태 6개 + 로켓그로스, 수십 초)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)"; - out.innerHTML = '' + loading + "
"; - try { - const to = document.getElementById("perf-probe-to").value || day; - const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) + - "&to=" + encodeURIComponent(to)); - if (!r.ok) { out.innerHTML = '' + esc((r.label ? r.label + " — " : "") + r.message) + "
"; return; } - // 원본 확인은 최대 31일 — 더 긴 기간을 넣으면 서버가 앞 31일만 본다. 실제 조회 기간을 꼭 보여 준다. - const shown = r.date ? (r.date === r.to ? r.date : r.date + " ~ " + r.to) : ""; - const cut = r.to && r.to < to; - const range = shown ? '조회 기간 ' + esc(shown) + "" + - (cut ? " — 원본 데이터 확인은 한 번에 31일까지라 " + esc(r.to) + " 뒤(~" + esc(to) + ")는 조회하지 않았습니다. " + - "1년치 매출은 위 [과거 매출 가져오기]로 받으세요(31일씩 나눠 불러 저장)." : "") + "
" : ""; - const summary = range + '| 조회 | ' + - '주소 | 결과 | 건수 |
|---|---|---|---|
| ' + esc(p.label) + ' | ' + esc(p.path) + " | " + - (p.ok ? '동작' : '실패 ' + esc(p.error) + "") + - ' | ' + (p.ok ? fmt(p.count) : "") + " |
| 항목 | 채워진 줄 | 숫자 합계 | ' + - '예시 값 |
|---|---|---|---|
| ' + esc(f.name) + ' | ' + fmt(f.filled) + ' | ' + - (f.sum == null ? "" : fmt(f.sum)) + " | " + (f.personal ? '개인정보(숨김)' : esc(f.sample)) + " |
규칙: ' + esc(r.rule) + "
" : "") + - '| 날짜 | 주문 수 | ' + - esc((r.day_cols || {}).amount || "매출") + " | " + - "" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + " | " + - esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + " |
|---|---|---|---|---|
| ' + esc(d.date) + ' | ' + fmt(d.orders) + - ' | ' + fmt(d.amount) + ' | ' + fmt(d.claimed || 0) + - ' | ' + fmt(d.ship || 0) + " |
| 합계 | ' + - ["orders", "amount", "claimed", "ship"].map(function (k) { - return '' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + " | "; - }).join("") + "
| 날짜 | ' + - rc.map(function (c) { return "" + esc(c.label) + " | "; }).join("") + "|
|---|---|---|
| ' + esc(dt) + " | " + rc.map(function (c) { - return '' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + " | "; - }).join("") + "|
| 합계 | ' + rc.map(function (c) { - if (c.error) return '실패 ' + esc(c.error) + " | "; - const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0); - return '' + fmt(t) + " | "; - }).join("") + "
' + esc(c.label) + " — " + fmt(c.rows.length) + "건
" + - '| 환불일 | 주문일 | ' + - '주문번호 | ' + - '주문상품 | 금액 | 메모 |
|---|---|---|---|---|---|
| ' + esc(x.date) + " | " + esc(x.orderDate || "") + " | " + - esc(x.orderId) + " | " + esc(x.orderProductId) + - ' | ' + fmt(x.amount) + ' | ' + esc(x.note) + " |
그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.
'); - } catch (err) { - out.innerHTML = '' + esc(err.message) + "
"; - } finally { probe.disabled = false; } - }); - // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ── const backfill = document.getElementById("perf-backfill"); if (backfill) backfill.addEventListener("click", async function () { diff --git a/app/static/project.css b/app/static/project.css index 4b25e67..b26969a 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -424,6 +424,19 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important; } .pj-card:hover { box-shadow: var(--pj-card-shadow-hover); transform: translateY(-1px); } .pj-card.is-dragging { opacity: .5; } +/* 카드 끌기 실시간 미리보기(2026-10-19) — 원래 카드는 숨기고 놓일 자리에 점선 자리 표시, + 끄는 모양은 살짝 기울어진 그림자 카드(setDragImage 용, 화면 밖에 잠깐 붙였다 뗀다). */ +.pj-card.is-drag-src { display: none; } +.pj-card-ph { + flex: none; box-sizing: border-box; border-radius: var(--pj-card-radius); + border: 2px dashed var(--pj-accent); background: var(--pj-accent-tint); + animation: pj-card-ph-in .16s ease-out; +} +@keyframes pj-card-ph-in { from { opacity: 0; } to { opacity: 1; } } +.pj-card-ghost { position: fixed; left: -10000px; top: 0; padding: 14px; pointer-events: none; } +.pj-card-ghost > .pj-card { + transform: rotate(2.5deg); box-shadow: 0 12px 28px rgba(0, 0, 0, .22); border-color: #c9c9cc; +} .pj-card.pj-tasknew { flex: none; min-height: 106px; box-sizing: border-box; border-color: #8b8c8d; cursor: default; } @@ -2908,10 +2921,11 @@ a.pj-meet-quick-done:hover { background: #e8f5ee; } .pj-meet-table { width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: var(--pj-text-size); - background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; color: var(--pj-ink); line-height: var(--pj-text-leading); + /* 테두리는 모두 검정(2026-10-19) — 바깥 아래선은 마지막 줄 칸 아래선이 대신한다(겹쳐 두꺼워지지 않게) */ + background: #fff; border: 1px solid #000; border-bottom: none; border-radius: 0; color: var(--pj-ink); line-height: var(--pj-text-leading); } .pj-meet-table th, .pj-meet-table td { - box-sizing: border-box; border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top; + box-sizing: border-box; border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 0; vertical-align: top; } .pj-meet-table tr > :last-child { border-right: none; } .pj-meet-table thead th { @@ -2935,9 +2949,13 @@ a.pj-meet-quick-done:hover { background: #e8f5ee; } .pj-meet-w-sec { width: 80px; } .pj-meet-w-label { width: 160px; } .pj-meet-w-amt { width: 122px; } -.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); } +.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); } .pj-meet-sec > tr > td.is-prev { background: #fafbfc; } -.pj-meet-sec > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); } +/* 항목 칸 끌어 옮기기 — 잡은 칸은 grab, 끄는 묶음은 연보라 + 왼쪽 보라 선, 끄는 동안 글자 선택 없음 */ +.pj-meet-sec th.pj-meet-c-label:has([data-meet-edit]) { cursor: grab; } +html.pj-meet-row-dragging, html.pj-meet-row-dragging * { cursor: grabbing !important; user-select: none !important; } +.pj-meet-table tr.is-meet-dragging > :not(.pj-meet-c-sec) { background-color: var(--pj-accent-tint) !important; } +.pj-meet-table tr.is-meet-dragging > th.pj-meet-c-label { box-shadow: inset 3px 0 0 var(--pj-accent); } .pj-meet-sec th { padding: 6px 8px; vertical-align: middle; text-align: center; } /* 구역·항목은 항상 세로 가운데 */ th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; vertical-align: middle; } .pj-meet-sec-add { diff --git a/app/static/project.js b/app/static/project.js index cd06427..c23e012 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -4746,26 +4746,31 @@ // 보드 드롭(전체보기) — 컬럼 이름(세션명)으로 옮긴다. 업무가 속한 '그 // 프로젝트'의 동일 이름 세션 id 를 찾아 적용(프로젝트마다 세션 id 가 다르다). function enableDropByName(body, name) { - body.addEventListener("dragover", function (e) { - if (!e.dataTransfer.types.includes("text/plain")) return; - e.preventDefault(); body.classList.add("is-over"); + // 전체 보기는 프로젝트마다 섹션이 달라 순서를 못 정한다 — 자리 표시는 섹션 맨 끝(제 섹션은 원래 자리) + wireCardPhOver(body, function () { return false; }); + // dragenter 도 받아 둔다 — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓아도 놓기가 거부되지 않게 + ["dragenter", "dragover"].forEach(function (kind) { + body.addEventListener(kind, function (e) { + if (!e.dataTransfer.types.includes("text/plain")) return; + e.preventDefault(); e.dataTransfer.dropEffect = "move"; + }); }); - body.addEventListener("dragleave", function () { body.classList.remove("is-over"); }); body.addEventListener("drop", async function (e) { if (!e.dataTransfer.types.includes("text/plain")) return; e.preventDefault(); - body.classList.remove("is-over"); const taskId = parseInt(e.dataTransfer.getData("text/plain"), 10); const t = tasks.find(function (x) { return x.id === taskId; }); - if (!t || (t.stage_name || "") === name) return; + if (!t || (t.stage_name || "") === name) { endCardDrag(true); return; } const plist = stagesByProject[t.project_id] || []; const target = plist.find(function (s) { return s.name === name; }); - if (!target) { alert("'" + (t.project_name || "이 프로젝트") + "' 에는 '" + name + "' 섹션이 없습니다."); return; } + if (!target) { endCardDrag(true); alert("'" + (t.project_name || "이 프로젝트") + "' 에는 '" + name + "' 섹션이 없습니다."); return; } + if (cardDrag) cardDrag.dropped = true; try { const res = await api("PUT", "/project/api/tasks/" + taskId, { stage_id: target.id }); mergeTask(res.task); - renderBoard(); } catch (err) { alert("이동 실패: " + err.message); } + endCardDrag(true); + renderBoard(); }); } @@ -5206,52 +5211,195 @@ } return cards.length; } - function enableDropByStageId(body, stageId) { - body.addEventListener("dragover", function (e) { - if (!e.dataTransfer.types.includes("text/plain")) return; - e.preventDefault(); body.classList.add("is-over"); + // ── 카드 끌기 실시간 미리보기(2026-10-19) — 끄는 동안 카드 자리는 비우고(자리 표시 + // .pj-card-ph), 마우스가 카드 사이를 지나는 순간 자리 표시가 그 사이로 옮겨 가며 다른 카드가 + // 미끄러지듯 비켜난다(FLIP 애니메이션). 놓으면 자리 표시가 있던 곳에 그대로 들어간다 — + // 섹션 안·다른 섹션 모두. 끄는 카드는 살짝 기울어진 그림자 카드로 마우스를 따라간다. + // 필터·정렬 중이거나 전체 보기(섹션 이름 보드)면 순서를 못 정하므로 원래 자리/섹션 맨 끝만. + let cardDrag = null; // { t, card, ph, fromBody, origIdx, dropped } + function phCards(body) { + return Array.prototype.filter.call(body.children, function (c) { + return c.classList.contains("pj-card") && c.dataset.taskId && (!cardDrag || c !== cardDrag.card); + }); + } + function phIndex(body) { // 자리 표시 앞에 있는 카드 수 = 놓을 자리 + const ph = cardDrag && cardDrag.ph; + if (!ph || ph.parentNode !== body) return -1; + return phCards(body).filter(function (c) { return c.compareDocumentPosition(ph) & Node.DOCUMENT_POSITION_FOLLOWING; }).length; + } + function startCardDrag(e, card, t) { + endCardDrag(true); + const body = card.parentNode; + if (!body || !body.classList.contains("pj-col-body")) return; + // 끄는 모양 — 카드 복제를 살짝 기울여 그림자와 함께(화면 배율 밖 body 에 잠깐 붙였다 뗀다) + try { + const r = card.getBoundingClientRect(); + const ghost = document.createElement("div"); + ghost.className = "pj-card-ghost"; + const clone = card.cloneNode(true); + clone.classList.remove("is-dragging"); + clone.style.width = card.offsetWidth + "px"; + ghost.appendChild(clone); + if (document.documentElement.classList.contains("pj-ui-scale")) ghost.style.zoom = "0.75"; + document.body.appendChild(ghost); + e.dataTransfer.setDragImage(ghost, Math.max(0, e.clientX - r.left) + 14, Math.max(0, e.clientY - r.top) + 14); + setTimeout(function () { ghost.remove(); }, 0); + } catch (_) {} + const ph = document.createElement("div"); + ph.className = "pj-card-ph"; + ph.style.height = card.offsetHeight + "px"; + // (cardDrag 를 정하기 전이라 phCards 에 끄는 카드도 들어 있다 — 그 순번 = 나머지 카드 중 원래 자리) + cardDrag = { t: t, card: card, ph: ph, fromBody: body, origIdx: phCards(body).indexOf(card), dropped: false }; + document.documentElement.classList.add("pj-card-dragging"); + // 끌기 그림이 찍힌 뒤에 원래 카드를 숨기고 그 자리에 자리 표시(같은 틱에 숨기면 크롬이 끌기를 취소) + const cur = cardDrag; + setTimeout(function () { + if (cardDrag !== cur || !card.isConnected) return; + card.parentNode.insertBefore(ph, card); + card.classList.add("is-drag-src"); + }, 0); + } + function endCardDrag(force) { + const d = cardDrag; + if (!d) return; + if (d.dropped && !force) return; // 놓은 뒤 저장 중 — 저장이 끝나면 다시 그리며 정리 + cardDrag = null; + document.documentElement.classList.remove("pj-card-dragging"); + d.ph.remove(); + d.card.classList.remove("is-drag-src", "is-dragging"); + document.querySelectorAll(".pj-col-body.is-over").forEach(function (b) { b.classList.remove("is-over"); }); + } + // 레이아웃 바꾸기 전후 위치 차이만큼 되돌렸다가 0 으로 — 비켜나는 카드가 미끄러지는 효과. + function flipBoardCards(bodies, mutate) { + const nodes = []; + bodies.forEach(function (b) { + if (!b) return; + Array.prototype.forEach.call(b.children, function (c) { + if ((c.classList.contains("pj-card") || c.classList.contains("pj-card-ph")) && nodes.indexOf(c) < 0) nodes.push(c); + }); + }); + const first = nodes.map(function (n) { const r = n.getBoundingClientRect(); return [r.left, r.top]; }); + mutate(); + nodes.forEach(function (n, i) { + if (!n.isConnected || n.classList.contains("is-drag-src")) return; + const r = n.getBoundingClientRect(); + const dx = first[i][0] - r.left, dy = first[i][1] - r.top; + if (!dx && !dy) return; + n.style.transition = "none"; + n.style.transform = "translate(" + dx + "px," + dy + "px)"; + }); + requestAnimationFrame(function () { + nodes.forEach(function (n) { + if (!n.style.transform) return; + n.style.transition = "transform .18s cubic-bezier(.2,.7,.3,1)"; + n.style.transform = ""; + setTimeout(function () { if (!n.style.transform) n.style.transition = ""; }, 220); + }); + }); + } + // 마우스 Y 가 이 섹션의 몇 번째 카드 사이인지 — 애니메이션 중인 카드는 움직이기 전 자리로 계산(떨림 방지). + function phTargetIndex(body, clientY, ordered) { + const cards = phCards(body); + if (!ordered) return body === cardDrag.fromBody ? Math.min(cardDrag.origIdx, cards.length) : cards.length; + for (let i = 0; i < cards.length; i++) { + const r = cards[i].getBoundingClientRect(); + let ty = 0; + if (cards[i].style.transform) { try { ty = new DOMMatrixReadOnly(getComputedStyle(cards[i]).transform).m42; } catch (_) {} } + if (clientY < r.top - ty + r.height / 2) return i; + } + return cards.length; + } + function placeCardPh(body, clientY, ordered) { + if (!cardDrag || !cardDrag.card.classList.contains("is-drag-src")) return; + const idx = phTargetIndex(body, clientY, ordered); + if (phIndex(body) === idx) return; + const ph = cardDrag.ph; + const oldBody = ph.parentNode; + flipBoardCards([oldBody, body], function () { + const cards = phCards(body); + if (idx < cards.length) body.insertBefore(ph, cards[idx]); + else if (cards.length) cards[cards.length - 1].after(ph); + else body.insertBefore(ph, body.querySelector(":scope > .pj-tasknew")); + }); + } + function wireCardPhOver(body, ordered) { + body.addEventListener("dragover", function (e) { + if (!cardDrag || !e.dataTransfer.types.includes("text/plain")) return; + placeCardPh(body, e.clientY, ordered()); + }); + } + function enableDropByStageId(body, stageId) { + wireCardPhOver(body, manualOrderAllowed); + // dragenter 도 받아 둔다 — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓아도 놓기가 거부되지 않게 + ["dragenter", "dragover"].forEach(function (kind) { + body.addEventListener(kind, function (e) { + if (!e.dataTransfer.types.includes("text/plain")) return; + e.preventDefault(); e.dataTransfer.dropEffect = "move"; + }); }); - body.addEventListener("dragleave", function () { body.classList.remove("is-over"); }); body.addEventListener("drop", async function (e) { if (!e.dataTransfer.types.includes("text/plain")) return; e.preventDefault(); - body.classList.remove("is-over"); const taskId = parseInt(e.dataTransfer.getData("text/plain"), 10); - const t = tasks.find(function (x) { return x.id === taskId; }); - if (!t) return; + const t = (cardDrag && cardDrag.t.id === taskId && cardDrag.t) || tasks.find(function (x) { return x.id === taskId; }); + if (!t) { endCardDrag(true); return; } + // 놓을 자리 = 자리 표시 위치(없으면 마우스 위치) + let idx = phIndex(body); + if (idx < 0) idx = cardDropIndex(body, e.clientY, taskId); + // 자리 표시 기준 이 섹션 카드 순서(끈 카드 포함) + 화면에 없는 이 섹션 업무는 뒤에 + const domIds = phCards(body).map(function (c) { return parseInt(c.dataset.taskId, 10); }) + .filter(function (id) { return id !== taskId; }); + domIds.splice(idx, 0, taskId); + function orderedFor() { + const rest = tasks.filter(function (x) { + return x.stage_id === stageId && x.context_project_id === projectId && domIds.indexOf(x.id) < 0; + }).map(function (x) { return x.id; }); + return domIds.concat(rest); + } if (t.stage_id === stageId) { if (!manualOrderAllowed()) { showToast("필터·정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (정렬: 기본, 필터 초기화 후 가능)", "error"); + endCardDrag(true); return; } // 같은 세션 안에서 카드 위치만 이동 — 세션 이동이 아니라 정렬. - const currentOrder = tasks.filter(function (x) { return x.stage_id === stageId; }); - const idx = cardDropIndex(body, e.clientY, taskId); - const withoutDragged = currentOrder.filter(function (x) { return x.id !== taskId; }); - withoutDragged.splice(idx, 0, t); - const orderedIds = withoutDragged.map(function (x) { return x.id; }); - const beforeIds = currentOrder.map(function (x) { return x.id; }); - if (beforeIds.join(",") === orderedIds.join(",")) return; // 놓은 자리가 원래 자리와 같으면 아무것도 안 함 + const beforeIds = tasks.filter(function (x) { return x.stage_id === stageId && x.context_project_id === projectId; }) + .map(function (x) { return x.id; }); + const orderedIds = orderedFor(); + if (beforeIds.join(",") === orderedIds.join(",")) { endCardDrag(true); return; } // 놓은 자리가 원래 자리와 같으면 아무것도 안 함 + if (cardDrag) cardDrag.dropped = true; // 저장하는 동안 놓은 자리 그대로 보인다 try { await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order", { ordered_ids: orderedIds }); applyStageOrder(stageId, orderedIds); - renderBoard(); } catch (err) { showToast("순서 변경 실패: " + err.message, "error"); } + endCardDrag(true); + renderBoard(); return; } + if (cardDrag) cardDrag.dropped = true; try { if (t.project_id === projectId) { const res = await api("PUT", "/project/api/tasks/" + taskId, { stage_id: stageId }); mergeTask(res.task); + // 다른 섹션에도 놓은 자리 그대로 — 기본 정렬·필터 없음일 때만 순서 저장(아니면 섹션 맨 끝) + if (manualOrderAllowed()) { + const orderedIds = orderedFor(); + try { + await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order", + { ordered_ids: orderedIds }); + applyStageOrder(stageId, orderedIds); + } catch (err) { showToast("섹션은 옮겼지만 순서 저장 실패: " + err.message, "error"); } + } } else { await api("POST", "/project/api/tasks/" + taskId + "/links", { project_id: projectId, stage_id: stageId }); t.stage_id = stageId; t.is_linked = true; } - renderBoard(); } catch (err) { showToast("이동 실패: " + err.message, "error"); } + endCardDrag(true); + renderBoard(); }); } @@ -6072,9 +6220,11 @@ e.dataTransfer.setData("text/plain", String(t.id)); // 왼쪽 프로젝트 목록에 놓으면 다른 프로젝트로 옮기기(원 소속 업무만 — 연결로 보이는 카드는 원 소속에서 옮긴다) if (t.context_project_id === t.project_id || !t.is_linked) e.dataTransfer.setData(TASK_DRAG_TYPE, String(t.id)); + e.dataTransfer.effectAllowed = "move"; card.classList.add("is-dragging"); + startCardDrag(e, card, t); }); - card.addEventListener("dragend", function () { card.classList.remove("is-dragging"); }); + card.addEventListener("dragend", function () { card.classList.remove("is-dragging"); endCardDrag(); }); // 세부 업무 줄을 이 카드에 놓으면 이 업무의 세부 업무로 옮긴다. // 원래 상위 업무 카드 위에서는 받지 않는다(제자리). card.addEventListener("dragover", function (e) { @@ -9625,6 +9775,8 @@ async function syncOnce() { // 회의록 패널을 보는 동안은 이전 프로젝트 화면의 자동 갱신이 왼쪽 메뉴를 다시 만들지 않게 한다. if (document.querySelector(".pj-meeting-panel-host")) return; + // 보드 카드를 끄는 중에는 다시 그리지 않는다(자리 표시·끄는 카드가 사라짐) — 다음 주기에 반영 + if (document.documentElement.classList.contains("pj-card-dragging")) return; if (syncing || observed === null || observed === applied) return; syncing = true; const target = observed; @@ -12381,6 +12533,115 @@ showContextMenu(x, y, items.concat(cellGrid ? [null].concat(cellGrid.widthItems(tr.querySelector("th.pj-meet-c-label"))) : [])); } + // ── 항목 칸 끌어 옮기기(2026-10-19) — 항목 칸을 잡고 위아래로 끌면 그 묶음(같은 항목 칸으로 이어 붙은 줄 + 걸친 세로 병합)이 + // 마우스를 따라 같은 구역의 묶음 사이로 실시간으로 옮겨 가고, 다른 줄은 미끄러지듯 비켜난다. 놓으면 move-to 저장 후 + // 표를 다시 그린다(실패하면 서버 순서로 되돌림). Esc = 취소. 살짝 누르기만 하면(5px 미만) 예전처럼 이름 수정. + if (canEdit) { + let press = null, rowDrag = null, noClickUntil = 0; + const meetUnits = function (tbody) { // 묶음 = 항목 칸 첫 줄부터(이어 붙은 줄·병합에 가려진 줄은 앞 묶음에) + const rows = Array.from(tbody.rows), covered = new Set(), out = []; + rows.forEach(function (tr, k) { + tr.querySelectorAll("td[data-meet-item]").forEach(function (td) { + for (let n = 1; n < (td.rowSpan || 1); n++) covered.add(k + n); + }); + }); + rows.forEach(function (tr, k) { + const start = !out.length || (tr.dataset.labelCont !== "1" && tr.querySelector("th.pj-meet-c-label") && !covered.has(k)); + if (start) out.push([tr]); else out[out.length - 1].push(tr); + }); + return out; + }; + const applyUnits = function (order) { // 줄을 이 순서로 다시 끼우고 FLIP(칸 단위 — 구분 칸은 첫 줄에 고정) + const d = rowDrag, cells = []; + d.tbody.querySelectorAll("tr > th, tr > td").forEach(function (c) { + if (c !== d.secTh) cells.push([c, c.getBoundingClientRect().top]); + }); + order.forEach(function (u) { u.forEach(function (tr) { d.tbody.appendChild(tr); }); }); + const first = d.tbody.rows[0]; + if (d.secTh && d.secTh.parentElement !== first) first.insertBefore(d.secTh, first.firstChild); + d.units = order; + if (!Element.prototype.animate) return; + cells.forEach(function (p) { + const dy = p[1] - p[0].getBoundingClientRect().top; + if (Math.abs(dy) > 0.5) { + p[0].animate([{ transform: "translateY(" + dy + "px)" }, { transform: "none" }], + { duration: 170, easing: "cubic-bezier(.2,.7,.3,1)" }); + } + }); + }; + const endRowDrag = function (cancel) { + const d = rowDrag; + rowDrag = null; + press = null; + if (!d) return null; + if (cancel && d.tbody.isConnected) { rowDrag = d; applyUnits(d.start); rowDrag = null; } + d.me.forEach(function (tr) { tr.classList.remove("is-meet-dragging"); }); + document.documentElement.classList.remove("pj-meet-row-dragging"); + noClickUntil = Date.now() + 350; + return d; + }; + table.addEventListener("mousedown", function (e) { + if (e.button !== 0 || rowDrag) return; + const th = e.target.closest("tbody.pj-meet-sec th.pj-meet-c-label"); + if (!th || e.target.closest("button, .is-editing, .pj-meet-colresize")) return; + press = { th: th, x: e.clientX, y: e.clientY }; + }); + document.addEventListener("mousemove", function (e) { + if (!press) return; + if (!rowDrag) { + if (Math.abs(e.clientY - press.y) < 5 || !press.th.isConnected) return; + const tr = press.th.parentElement, tbody = tr.closest("tbody"); + const units = meetUnits(tbody); + const me = units.find(function (u) { return u.indexOf(tr) >= 0; }); + if (!me || units.length < 2) { press = null; return; } + rowDrag = { tbody: tbody, units: units, start: units.slice(), me: me, secTh: tbody.querySelector("th.pj-meet-c-sec") }; + me.forEach(function (r) { r.classList.add("is-meet-dragging"); }); + document.documentElement.classList.add("pj-meet-row-dragging"); + try { window.getSelection().removeAllRanges(); } catch (_) {} + } + e.preventDefault(); + const d = rowDrag; + if (!d.tbody.isConnected) { endRowDrag(false); return; } // 그 사이 표를 다시 그림 + const others = d.units.filter(function (u) { return u !== d.me; }); + let idx = others.length; + for (let i = 0; i < others.length; i++) { + const top = others[i][0].getBoundingClientRect().top; + const bottom = others[i][others[i].length - 1].getBoundingClientRect().bottom; + if (e.clientY < (top + bottom) / 2) { idx = i; break; } + } + const order = others.slice(); + order.splice(idx, 0, d.me); + if (order.every(function (u, k) { return u === d.units[k]; })) return; + applyUnits(order); + }); + document.addEventListener("mouseup", function () { + const d = endRowDrag(false); + if (!d || !d.tbody.isConnected) return; + const k = d.units.indexOf(d.me); + if (k === d.start.indexOf(d.me)) return; // 제자리 + const next = d.units[k + 1]; + const moveId = d.me[0].dataset.item, before = next ? parseInt(next[0].dataset.item, 10) : null; + run(async function () { + try { + await api("POST", itemUrl(moveId) + "/move-to", { before_item_id: before }); + } catch (err) { + showToast("옮기지 못했습니다: " + err.message, "error"); + await refreshMeeting(); // 서버 순서로 되돌림 + return false; + } + return true; + }); + }); + document.addEventListener("keydown", function (e) { + if (e.key === "Escape" && rowDrag) { e.preventDefault(); e.stopPropagation(); endRowDrag(true); } + }, true); + window.addEventListener("blur", function () { if (rowDrag) endRowDrag(true); else press = null; }); + // 끌기를 끝낸 바로 뒤 클릭은 이름 수정으로 넘기지 않는다 + table.addEventListener("click", function (e) { + if (Date.now() < noClickUntil) { e.preventDefault(); e.stopImmediatePropagation(); } + }, true); + } + // ── 줄 구조가 바뀐 뒤(줄 추가·삭제·이동·항목 칸 나누기·구역 이동·셀 병합) 새로고침 없이 표의 구역 부분만 서버에서 다시 받아 // 그 자리에서 바꿔 끼운다(연간 목표 refreshTable 과 같은 방식) — 지운 줄은 흐려지며 사라지고, 남은 줄은 예전 자리에서 // 새 자리로 미끄러지고(FLIP), 새 줄은 위에서 내려오며 잠깐 강조. 동작 줄이기 설정이면 애니메이션 없이. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 6264b8b..a7e0346 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -352,6 +352,18 @@ ## 7. 화면 +- **2026-10-19 변경** + - **설정 진단 카드 삭제** — "쇼핑몰 원본 데이터 확인"·"카페24 매출 대조"·"일별 한 번에 비교" 카드와 그 화면 스크립트를 뺐다 + (사용자 요청 — 쇼핑몰별 규칙 대조가 끝나 더 안 씀). 서버 API `GET /api/marketplaces/{code}/reconcile`·`daily-check` 와 + 어댑터 `reconcile`은 다시 대조가 필요할 때를 위해 남겼다(화면 진입점 없음). 아래 절의 "원본 데이터 확인"·"매출 대조" 설명은 그 당시 기록. + - **보기 설정 · 매출 단위** — 설정 화면 "보기 설정" 카드(모듈 권한자 누구나): 원·천원·백만원. 이 브라우저 쿠키 `perf_unit`(1년, path `/performance`)에 두고 + 매출 실적 화면을 서버가 그 단위로 그린다(`dashboard.amount_text` — 천원 = 정수 반올림, 백만원 = 소수 한 자리, `router._unit_ctx` → 템플릿 `amt`·`money`). + 표·월/연 누적 카드 머리에 "단위: 천원", KPI·연 누적은 "3,835천원". 수동 입력은 늘 원 단위로 넣는다(입력 직후 칸은 JS `unitWon`). 광고비 탭·그래프 말풍선은 원 그대로. + - **매출 칸 아래 광고비(ROAS%)** — 일자별 × 쇼핑몰 표의 매출 칸마다 그 쇼핑몰 광고비와 ROAS 를 광고비 색(`--perf-ad`) 작은 줄로(`dashboard._ad_lines`). + 값은 광고비 탭과 같다(`ad_spend.channel_roas` — 구글·메타·네이버는 보고서 ROAS, 나머지는 그 쇼핑몰 매출 ÷ 광고비). 쇼핑몰 → 채널(`sales_ad_channels`): + 카페24 = **구글·메타 두 줄**("구글 100,000(413%)"), 네이버 = 네이버 광고, 쿠팡 = 쿠팡(윙), 그 밖은 같은 코드 채널. 일 합계 칸 = 보이는 쇼핑몰 광고비 합(ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합), + 주간합계·기간 합계 행도 그 기간 값. 광고비가 없는 칸은 줄 없음, 광고비 표(005) 미적용·조회 실패면 줄 없이 매출만. 총매출·수수료·차감 매출 전환과 무관하게 늘 보인다. + - **탭**(2026-10-13): 왼쪽 위 큰 탭 둘 — [매출 실적](검정, `/performance/`) · [광고비](주황, `/performance/ads`) — 아이콘 + 고른 탭 색으로 구분, 설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols `settings`, `/performance/settings`). `_tabs.html`. - **광고비** `/performance/ads?period=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널, diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index dbf3ae3..e500ff5 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -1384,6 +1384,24 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame - 검증: `tests/test_project_module.py::test_review_meeting_apply_is_one_transaction`(실제 PostgreSQL — 테스트 전용 트리거로 연결 실패 주입, 풀 1개, 줄 바뀜 409), 기존 `test_review_meeting_quick_tasks_shared`(동시 4건), `tests/js/goals_meeting_ui.test.js` [2g9]. +## 6-23. 보드 카드 끌기 실시간 미리보기 · 회의록 항목 칸 끌어 옮기기 · 회의록 표 검정 테두리 (2026-10-19, 마이그레이션 없음) + +- **보드 카드 끌기**(`project.js` `startCardDrag`·`placeCardPh`·`flipBoardCards`·`endCardDrag`) — 네이티브 HTML5 DnD 그대로(왼쪽 프로젝트 목록 이동 6-18·세부 업무 끌기와 같은 이벤트). + - dragstart: 카드 복제를 `.pj-card-ghost`(body 에 잠깐, 화면 배율이면 zoom .75) 안에서 2.5° 기울여 `setDragImage`. 다음 틱에 원래 카드를 `.is-drag-src`(display none)로 숨기고 + 그 자리에 같은 높이의 점선 자리 표시 `.pj-card-ph`(같은 틱에 숨기면 크롬이 끌기를 취소). + - dragover(섹션 body): 마우스 Y 가 카드 중간선 위/아래 어디인지(애니메이션 중인 카드는 transform 을 빼고 계산 — 떨림 방지)로 자리 표시를 옮기고, 옮기기 전후 위치 차이로 + FLIP(transform .18s) — 다른 카드가 미끄러지듯 비켜난다. 섹션을 넘어가도 같음. 순서를 못 정하는 경우(필터·정렬 중, 전체 보기 섹션 이름 보드)는 제 섹션 = 원래 자리, 다른 섹션 = 맨 끝. + - drop: 자리 표시 위치 = 놓을 자리. 같은 섹션 = `PUT stages/{id}/tasks/order`, 다른 섹션 = `PUT tasks/{id} {stage_id}` 뒤 그 섹션 `tasks/order`(기본 정렬·필터 없음일 때만, + 화면 카드 순서 + 화면에 없는 그 섹션 업무는 뒤). 멀티호밍 연결 업무는 예전처럼 links 만(순서 저장 없음). 저장하는 동안 놓은 모양 유지(`dropped`) → 끝나면 `renderBoard`. + - 섹션 밖에 놓거나 취소하면 dragend 가 자리 표시를 지우고 카드를 원래 자리에 다시 보인다. 끄는 동안 `html.pj-card-dragging` — 실시간 동기화(`syncOnce`)가 보드를 다시 그리지 않는다(다음 주기 반영). + - **body 는 dragenter 도 preventDefault** — 자리 표시가 마우스 아래로 들어온 직후(다음 dragover 전) 놓으면 drop 이 거부되던 문제(Playwright 실제 크롬으로 재현). +- **회의록 항목 칸 끌어 옮기기** — 항목(`th.pj-meet-c-label`)을 마우스로 5px 이상 끌면 시작(그보다 짧으면 이름 수정 클릭 그대로, 끈 뒤 클릭은 막음). + - 묶음 = 항목 칸 첫 줄부터 이어 붙은 줄(`data-label-cont`)·주요 업무 세로 병합에 가려진 줄까지(서버 `move_meeting_group` 과 같은 경계). 묶음이 둘 이상인 구역만. + - 끄는 동안 그 묶음 tr 을 다른 묶음 중간선 기준으로 바로 옮겨 끼우고(구분 칸 `th.pj-meet-c-sec` 은 늘 구역 첫 줄로 옮김), 칸 단위 FLIP(`Element.animate` .17s). 끄는 줄은 연보라 + 왼쪽 보라 선. + - 놓으면 `POST /api/goals/meeting-items/{id}/move-to {before_item_id: 다음 묶음 첫 줄 | null = 구역 맨 끝}` → `refreshMeeting`. 실패하면 안내 후 서버 순서로 다시 그림. Esc = 원래 순서로. + - `db.move_meeting_group`: 같은 주 잠금(`_locked_meeting_items`, 회의 완료면 409)·묶음째·같은 구역만(다른 구역 400)·묶음 사이 자리(`before` 가 묶음 첫 줄이 아님) 409·제자리면 그대로. 권한은 줄 순서와 같음(누구나, 완료 전). +- **회의록 표 테두리** — `.pj-meet-table` 바깥·칸 테두리 모두 `#000`(예전 연회색). 칸은 오른쪽·아래 선만 그리므로 표 바깥 아래선은 없애(마지막 줄 아래선이 대신) 두 줄로 겹치지 않게, 모서리 둥글림 0. 구역 첫 줄 위 진한 선은 없앰(검정 1px 로 통일). + ## 7. 추후 단계 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성. diff --git a/tests/test_project_meeting_cells.py b/tests/test_project_meeting_cells.py index 5562199..e4f4ce0 100644 --- a/tests/test_project_meeting_cells.py +++ b/tests/test_project_meeting_cells.py @@ -177,6 +177,36 @@ class MeetingCellTests(unittest.TestCase): with self.assertRaises(ValueError): self.st.move_meeting_item(item_id=3, direction=-1) + def _order(self): + return [r["id"] for r in sorted(self.conn.rows.values(), key=lambda r: r["sort_order"])] + + def test_drag_move_group_to_position_in_section(self): + """항목 칸 끌어 옮기기(move_meeting_group) — 묶음째로 같은 구역의 묶음 앞/맨 끝, 묶음 사이·다른 구역은 거절.""" + self.assertTrue(self.st.move_meeting_group(item_id=3, before_item_id=1)) + self.assertEqual(self._order(), [3, 1, 2, 4]) + self.assertTrue(self.conn.locked is False and self.conn.writes == 4) + self.assertFalse(self.st.move_meeting_group(item_id=3, before_item_id=3)) # 제자리 + with self.assertRaises(ValueError): + self.st.move_meeting_group(item_id=1, before_item_id=4) # 다른 구역 + with self.assertRaises(KeyError): + self.st.move_meeting_group(item_id=1, before_item_id=99) + + def test_drag_move_keeps_label_group_and_merge_together(self): + for n in range(1, 5): + self.conn.rows[n]["sort_order"] = n + self.conn.rows[2]["label_cont"] = True # 줄1·줄2 = 한 항목 칸 + self.assertTrue(self.st.move_meeting_group(item_id=2, before_item_id=None)) # 이어 붙은 줄을 잡아도 묶음째 + self.assertEqual(self._order(), [3, 1, 2, 4]) + with self.assertRaises(store.GoalCellConflict): + self.st.move_meeting_group(item_id=3, before_item_id=2) # 묶음 사이에는 못 넣음 + self.conn.rows[2]["label_cont"] = False + for n in range(1, 5): + self.conn.rows[n]["sort_order"] = n + self.conn.rows[1]["content_row_span"] = 2 # 주요 업무 칸 1~2 병합 → 같이 움직인다 + self.assertTrue(self.st.move_meeting_group(item_id=3, before_item_id=1)) + self.assertEqual(self._order(), [3, 1, 2, 4]) + self.assertEqual(self.conn.rows[1]["content_row_span"], 2) + def test_plain_and_rich_saves_share_move_lock_and_visible_length_limit(self): rich = store.GOAL_RICH_PREFIX + json.dumps([dict(text="가", bold=True)] * 4000) out = self.st.update_meeting_item(item_id=1, fields={"content": rich})