Compare commits
96 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c23d1e3ce5 | |||
| bab495d9f2 | |||
| bbe27eac8b | |||
| 53896f0425 | |||
| db73faf270 | |||
| e3bc9d518d | |||
| 15a5eddf20 | |||
| e9fb1c3407 | |||
| 240d61c903 | |||
| e645f4beef | |||
| 4466601c58 | |||
| c3cab212b6 | |||
| b61c0897cc | |||
| 5c05f471b3 | |||
| 4e159e94e7 | |||
| db05538664 | |||
| ea7817752d | |||
| 67001f0a6e | |||
| c30ef72c6e | |||
| 581e0cf325 | |||
| e6b2812624 | |||
| 30fd2c5470 | |||
| 2df86983da | |||
| 90332bcb59 | |||
| 1c42ed5dd3 | |||
| 779cc79a87 | |||
| 1ba494dab8 | |||
| ef38140673 | |||
| 099271fdb2 | |||
| e6d38f342f | |||
| f8245b4499 | |||
| 9a8aea6435 | |||
| eab6b836d2 | |||
| deb5bfb9a1 | |||
| 4d3b747ab7 | |||
| 5471cbc32b | |||
| 4c94bf1293 | |||
| f36f7d3ad4 | |||
| 5bd0a5c406 | |||
| c317d7bb5d | |||
| 941b35a7a6 | |||
| ecc6405299 | |||
| 028831694a | |||
| 542e7fb7d1 | |||
| ac0f48bfce | |||
| 68bf43ea2f | |||
| cf7c44ce49 | |||
| db3b7d500d | |||
| d5fd617425 | |||
| bed3d4fc89 | |||
| 822c955bb6 | |||
| 20a79f5719 | |||
| b4edc16785 | |||
| 66db501170 | |||
| ac01a33c47 | |||
| 513aece27e | |||
| 1d3573a44a | |||
| 410d4fe05c | |||
| c15a746ae4 | |||
| da46abd678 | |||
| d38d00b4d2 | |||
| 8201fde606 | |||
| 70bf263a80 | |||
| 5a2c6ba2ad | |||
| 6ebf705e27 | |||
| 22490664d6 | |||
| 0c6dacb824 | |||
| 6345b69816 | |||
| 3882836fd5 | |||
| 59add598fa | |||
| ca2821464f | |||
| 24950c94ce | |||
| 454b3cc700 | |||
| dd1bc310dc | |||
| 53bead6691 | |||
| 36283ae265 | |||
| 89d204b2fe | |||
| 724b590868 | |||
| e130bbe577 | |||
| bc62e53270 | |||
| 6fd01314d5 | |||
| 1bdcd59287 | |||
| b7c0f28ad2 | |||
| 4320766abd | |||
| e934dd6abf | |||
| 18ac8f0761 | |||
| b5be26089d | |||
| 3a9a94f97b | |||
| c69bc0e9f3 | |||
| 833dbb5fdf | |||
| 2aa6b6efae | |||
| 1759e00213 | |||
| fa6e7066ae | |||
| 7cdca852bd | |||
| ee09e8bfd1 | |||
| ae6b6ec603 |
@@ -169,6 +169,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# APP_ENCRYPTION_KEY_V1=
|
||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||
# PERFORMANCE_SYNC_DAYS=7
|
||||
# 매출 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 매일 09:00~19:00 정각·30분마다 오늘 포함 최근 10일.
|
||||
# PERFORMANCE_AUTO_SYNC=false # 끄기
|
||||
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||
|
||||
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||
|
||||
@@ -27,3 +27,6 @@ tests/js/.out/
|
||||
|
||||
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||
KING-DESKTOP.XML
|
||||
|
||||
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||
~$*
|
||||
|
||||
+11
-1
@@ -26,6 +26,8 @@ from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||
from .modules.malaysia import router as malaysia_router
|
||||
from .modules.notice import build_notice_store
|
||||
from .modules.notice import router as notice_router
|
||||
from .modules.performance import build_performance_store
|
||||
from .modules.performance import router as performance_router
|
||||
from .modules.project import build_project_store
|
||||
@@ -115,10 +117,14 @@ def build_google_oauth() -> OAuth:
|
||||
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
||||
"""앱 시작 시 백그라운드 작업 시작.
|
||||
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
|
||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
|
||||
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
|
||||
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
|
||||
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
|
||||
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
||||
|
||||
start_reminder_thread(getattr(app_.state, "project_store", None))
|
||||
start_auto_sync_thread(app_.state)
|
||||
yield
|
||||
|
||||
|
||||
@@ -146,6 +152,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||
BASE_DIR / "modules" / "performance" / "templates",
|
||||
BASE_DIR / "modules" / "asset" / "templates",
|
||||
BASE_DIR / "modules" / "notice" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -209,6 +216,8 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
|
||||
app.state.notice_store = build_notice_store(app.state.project_store)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -220,6 +229,7 @@ app.include_router(project_router)
|
||||
app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
app.include_router(asset_router)
|
||||
app.include_router(notice_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import calendar as _calendar
|
||||
import json
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from fractions import Fraction
|
||||
from typing import Any
|
||||
|
||||
@@ -413,6 +414,17 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
||||
total_qty = sum(it["quantity"] for it in items)
|
||||
box_list = _expand_box_list(ship, calc, items)
|
||||
box_weight = _attach_box_weights(store, box_list)
|
||||
# 상자 목록 합계 행 — 수량 합계와 무게 합계(kg, 소수 첫째 자리)
|
||||
box_qty_total = sum(int(it.get("quantity") or 0) for b in box_list for it in (b.get("items") or []))
|
||||
box_weight_total = None
|
||||
box_weight_partial = False
|
||||
if box_weight:
|
||||
for b in box_list:
|
||||
b["weight_kg"] = _g_to_kg(b.get("weight_g"))
|
||||
if b.get("weight_g") is not None:
|
||||
box_weight_total = (box_weight_total or 0) + int(b["weight_g"])
|
||||
if b.get("weight_missing"):
|
||||
box_weight_partial = True
|
||||
|
||||
return render_template(
|
||||
request,
|
||||
@@ -429,6 +441,9 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
||||
"box_list": box_list,
|
||||
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
||||
"box_weight": box_weight,
|
||||
"box_qty_total": box_qty_total,
|
||||
"box_weight_total_kg": _g_to_kg(box_weight_total),
|
||||
"box_weight_partial": box_weight_partial,
|
||||
"total_qty": total_qty,
|
||||
},
|
||||
)
|
||||
@@ -1190,6 +1205,14 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _g_to_kg(grams: Any) -> str | None:
|
||||
"""g → kg 표시 글자 — 소수 둘째 자리에서 반올림(사사오입)해 첫째 자리까지. 예: 1,250g → "1.3"."""
|
||||
if grams is None:
|
||||
return None
|
||||
kg = (Decimal(int(grams)) / 1000).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
|
||||
return f"{kg:,.1f}"
|
||||
|
||||
|
||||
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
||||
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||
@@ -73,7 +73,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cpg-sum-scroll">
|
||||
<div class="cpg-sum-scroll cpg-boxno-scroll">
|
||||
<table class="erp-table cpg-boxno-table">
|
||||
<colgroup>
|
||||
<col class="cpg-boxno-c-no" />
|
||||
@@ -101,7 +101,7 @@
|
||||
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
||||
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
||||
{%- if b.weight_g is not none -%}
|
||||
{{ "{:,}".format(b.weight_g) }}<span class="cpg-weight-unit">g</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||
{{ b.weight_kg }}<span class="cpg-weight-unit">kg</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||
</td>
|
||||
{% endif %}
|
||||
@@ -112,6 +112,23 @@
|
||||
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
{% if box_list %}
|
||||
{# 합계 행 — 수량 합계, 무게 합계(kg). 무게 없는 제품이 있으면 아는 무게만 더한 값 #}
|
||||
<tfoot>
|
||||
<tr class="cpg-boxno-total">
|
||||
<td class="cpg-boxno-cell" colspan="3">합계</td>
|
||||
<td class="cpg-calc-num">{{ "{:,}".format(box_qty_total) }}</td>
|
||||
{% if box_weight %}
|
||||
<td class="cpg-boxno-weight"
|
||||
{% if box_weight_partial %}title="포장무게 미입력 제품이 있어 아는 무게만 더한 합계 (설정(제품명)에서 입력)"{% endif %}>
|
||||
{%- if box_weight_total_kg is not none -%}
|
||||
{{ box_weight_total_kg }}<span class="cpg-weight-unit">kg</span>{% if box_weight_partial %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
</tfoot>
|
||||
{% endif %}
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""긴급 공지 — ERP 전체 화면 가운데에 띄우는 공지(2026-10-12).
|
||||
|
||||
- 라우터: `router.py` (prefix=/notice) — 만들기·고치기는 수퍼관리자만, 받기·[확인]은 로그인 사용자 누구나
|
||||
- 저장소: `db.py` (project_db 마이그레이션 024 의 urgent_notice* 표 — 프로젝트 저장소의 연결 풀을 같이 쓴다)
|
||||
- 검증: `store.py`
|
||||
- 화면: 관리 `templates/notice/admin.html` + `static/erp-notice-admin.js`, 표시 `static/erp-notice.js`(erp_base.html 공용)
|
||||
상세는 docs/NOTICE_MODULE.md.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .router import router
|
||||
|
||||
__all__ = ["router", "build_notice_store"]
|
||||
|
||||
|
||||
def build_notice_store(project_store: Any) -> Any:
|
||||
"""프로젝트 저장소(PROJECT_DB_URL)가 있으면 그 연결 풀로 NoticeStore, 없으면 None(공지 API 는 503)."""
|
||||
if project_store is None:
|
||||
return None
|
||||
from .db import NoticeStore # noqa: WPS433
|
||||
|
||||
return NoticeStore(project_store.pool)
|
||||
@@ -0,0 +1,208 @@
|
||||
"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from psycopg import errors as psycopg_errors
|
||||
|
||||
from app.modules.project import store as pj_store
|
||||
from app.timezone import KST
|
||||
|
||||
from . import store
|
||||
|
||||
|
||||
def _iso(v: Any) -> str:
|
||||
return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else ""
|
||||
|
||||
|
||||
class NoticeStore:
|
||||
def __init__(self, pool: Any) -> None:
|
||||
self._pool = pool
|
||||
|
||||
def _conn(self) -> Any:
|
||||
return self._pool.connection()
|
||||
|
||||
@staticmethod
|
||||
def _run(fn: Any) -> Any:
|
||||
try:
|
||||
return fn()
|
||||
except psycopg_errors.UndefinedTable:
|
||||
raise store.NoticeMigrationNeeded()
|
||||
|
||||
# ── 읽기 ────────────────────────────────────────────────
|
||||
@staticmethod
|
||||
def _row(r: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": int(r["id"]), "title": r["title"], "body_html": r["body_html"],
|
||||
"show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]),
|
||||
"created_by": r["created_by"], "created_at": _iso(r["created_at"]),
|
||||
"updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")),
|
||||
"cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "",
|
||||
}
|
||||
|
||||
def list_notices(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||
"""관리 화면 — 최근 것부터. 받는 사람·확인한 사람 목록을 함께."""
|
||||
def run() -> list[dict[str, Any]]:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute("SELECT * FROM urgent_notices ORDER BY show_at DESC, id DESC LIMIT %s",
|
||||
(int(limit),)).fetchall()
|
||||
ids = [int(r["id"]) for r in rows]
|
||||
targets: dict[int, list[str]] = {i: [] for i in ids}
|
||||
acks: dict[int, dict[str, str]] = {i: {} for i in ids}
|
||||
if ids:
|
||||
for t in conn.execute("SELECT notice_id, user_email FROM urgent_notice_targets "
|
||||
"WHERE notice_id = ANY(%s) ORDER BY user_email", (ids,)).fetchall():
|
||||
targets[int(t["notice_id"])].append(t["user_email"])
|
||||
for a in conn.execute("SELECT notice_id, user_email, acked_at FROM urgent_notice_acks "
|
||||
"WHERE notice_id = ANY(%s) ORDER BY acked_at", (ids,)).fetchall():
|
||||
acks[int(a["notice_id"])][a["user_email"]] = _iso(a["acked_at"])
|
||||
return [{**self._row(r), "targets": targets[int(r["id"])], "acks": acks[int(r["id"])]} for r in rows]
|
||||
return self._run(run)
|
||||
|
||||
def pending_for(self, *, email: str, now: datetime | None = None) -> list[dict[str, Any]]:
|
||||
"""이 사람이 지금 봐야 할 공지 — 취소 안 됨·띄울 시각이 지남·받는 사람(전체 또는 지정)·아직 [확인] 안 함. 오래된 것부터."""
|
||||
em = pj_store.norm_str(email, lower=True)
|
||||
|
||||
def run() -> list[dict[str, Any]]:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT n.* FROM urgent_notices n "
|
||||
"WHERE n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||
" AND NOT EXISTS (SELECT 1 FROM urgent_notice_acks a WHERE a.notice_id = n.id AND a.user_email = %s) "
|
||||
"ORDER BY n.show_at ASC, n.id ASC LIMIT 20",
|
||||
(now or datetime.now(KST), em, em),
|
||||
).fetchall()
|
||||
return [self._row(r) for r in rows]
|
||||
return self._run(run)
|
||||
|
||||
def get_notice(self, *, notice_id: int) -> dict[str, Any] | None:
|
||||
def run() -> dict[str, Any] | None:
|
||||
with self._conn() as conn:
|
||||
r = conn.execute("SELECT * FROM urgent_notices WHERE id = %s", (notice_id,)).fetchone()
|
||||
if r is None:
|
||||
return None
|
||||
t = [x["user_email"] for x in conn.execute(
|
||||
"SELECT user_email FROM urgent_notice_targets WHERE notice_id = %s ORDER BY user_email",
|
||||
(notice_id,)).fetchall()]
|
||||
return {**self._row(r), "targets": t}
|
||||
return self._run(run)
|
||||
|
||||
def is_recipient(self, *, notice: dict[str, Any], email: str) -> bool:
|
||||
em = pj_store.norm_str(email, lower=True)
|
||||
return bool(notice["to_all"]) or em in notice.get("targets", [])
|
||||
|
||||
# ── 쓰기 ────────────────────────────────────────────────
|
||||
def _link_images(self, conn: Any, notice_id: int, body: str, by: str) -> None:
|
||||
"""본문에 든 이미지를 이 공지에 묶는다 — 내가 올린, 아직 어느 공지에도 안 묶인 이미지만(남의 공지 이미지 가로채기 방지)."""
|
||||
ids = store.image_ids_in(body)
|
||||
if ids:
|
||||
conn.execute("UPDATE urgent_notice_images SET notice_id = %s "
|
||||
"WHERE id = ANY(%s) AND notice_id IS NULL AND uploaded_by = %s", (notice_id, ids, by))
|
||||
# 하루 넘게 어느 공지에도 안 묶인 이미지(올렸다가 저장 안 함)는 정리
|
||||
conn.execute("DELETE FROM urgent_notice_images WHERE notice_id IS NULL AND created_at < now() - interval '1 day'")
|
||||
|
||||
def create_notice(self, *, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any, by: str) -> dict[str, Any]:
|
||||
ttl = store.validate_title(title)
|
||||
html = store.sanitize_body(body)
|
||||
when = store.parse_show_at(show_at)
|
||||
all_, emails = store.validate_targets(to_all, targets)
|
||||
who = pj_store.norm_str(by, lower=True)
|
||||
|
||||
def run() -> int:
|
||||
with self._conn() as conn:
|
||||
with conn.transaction():
|
||||
nid = int(conn.execute(
|
||||
"INSERT INTO urgent_notices (title, body_html, show_at, to_all, created_by, updated_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", (ttl, html, when, all_, who, who),
|
||||
).fetchone()["id"])
|
||||
for em in emails:
|
||||
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||
"ON CONFLICT DO NOTHING", (nid, em))
|
||||
self._link_images(conn, nid, html, who)
|
||||
return nid
|
||||
return self.get_notice(notice_id=self._run(run)) # type: ignore[return-value]
|
||||
|
||||
def update_notice(self, *, notice_id: int, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any,
|
||||
by: str, reshow: bool = False) -> dict[str, Any]:
|
||||
"""고치기 — 받는 사람·시각·내용 전부. reshow=True 면 이미 [확인]한 사람에게도 다시 띄운다(확인 기록 지움)."""
|
||||
ttl = store.validate_title(title)
|
||||
html = store.sanitize_body(body)
|
||||
when = store.parse_show_at(show_at)
|
||||
all_, emails = store.validate_targets(to_all, targets)
|
||||
who = pj_store.norm_str(by, lower=True)
|
||||
|
||||
def run() -> None:
|
||||
with self._conn() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute("UPDATE urgent_notices SET title=%s, body_html=%s, show_at=%s, to_all=%s, "
|
||||
"updated_by=%s, updated_at=now() WHERE id=%s RETURNING id",
|
||||
(ttl, html, when, all_, who, notice_id)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(notice_id)
|
||||
conn.execute("DELETE FROM urgent_notice_targets WHERE notice_id = %s", (notice_id,))
|
||||
for em in emails:
|
||||
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||
"ON CONFLICT DO NOTHING", (notice_id, em))
|
||||
if reshow:
|
||||
conn.execute("DELETE FROM urgent_notice_acks WHERE notice_id = %s", (notice_id,))
|
||||
self._link_images(conn, notice_id, html, who)
|
||||
self._run(run)
|
||||
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||
|
||||
def cancel_notice(self, *, notice_id: int, by: str, cancel: bool = True) -> dict[str, Any]:
|
||||
"""취소(더 띄우지 않음) · 취소 되돌리기. 기록은 남는다."""
|
||||
def run() -> None:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute(
|
||||
"UPDATE urgent_notices SET cancelled_at = CASE WHEN %s THEN now() ELSE NULL END, "
|
||||
"cancelled_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() WHERE id = %s RETURNING id",
|
||||
(cancel, cancel, pj_store.norm_str(by, lower=True), notice_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(notice_id)
|
||||
self._run(run)
|
||||
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||
|
||||
def ack(self, *, notice_id: int, email: str) -> bool:
|
||||
"""[확인] — 처음이면 True(이미 확인했으면 False). 받는 사람·표시 시각 확인은 라우터가 먼저 한다."""
|
||||
def run() -> bool:
|
||||
with self._conn() as conn:
|
||||
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
|
||||
"ON CONFLICT DO NOTHING RETURNING notice_id",
|
||||
(notice_id, pj_store.norm_str(email, lower=True))).fetchone()
|
||||
return r is not None
|
||||
return self._run(run)
|
||||
|
||||
# ── 이미지 ──────────────────────────────────────────────
|
||||
def add_image(self, *, data: bytes, filename: str, by: str) -> dict[str, Any]:
|
||||
ctype = store.sniff_image(data)
|
||||
|
||||
def run() -> int:
|
||||
with self._conn() as conn:
|
||||
return int(conn.execute(
|
||||
"INSERT INTO urgent_notice_images (filename, content_type, size_bytes, data, uploaded_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||
(pj_store.norm_str(filename)[:200], ctype, len(data), data, pj_store.norm_str(by, lower=True)),
|
||||
).fetchone()["id"])
|
||||
iid = self._run(run)
|
||||
return {"id": iid, "url": f"/notice/images/{iid}", "content_type": ctype}
|
||||
|
||||
def get_image(self, *, image_id: int) -> dict[str, Any] | None:
|
||||
def run() -> dict[str, Any] | None:
|
||||
with self._conn() as conn:
|
||||
r = conn.execute("SELECT id, notice_id, content_type, data, uploaded_by FROM urgent_notice_images "
|
||||
"WHERE id = %s", (image_id,)).fetchone()
|
||||
return dict(r) if r else None
|
||||
return self._run(run)
|
||||
|
||||
def enabled(self) -> bool:
|
||||
try:
|
||||
with self._conn() as conn:
|
||||
return bool(conn.execute("SELECT to_regclass('public.urgent_notices') AS r").fetchone()["r"])
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""긴급 공지 라우터(/notice) — ERP 전체 화면 가운데 공지.
|
||||
|
||||
- 만들기·고치기·취소·이미지 올리기·확인 현황: 수퍼관리자(app.store.SUPER_ADMIN_EMAIL)만.
|
||||
- 받기(GET /notice/api/pending)·[확인]: 로그인한 등록 사용자 누구나 — 모듈 권한과 무관(ERP 전체 공지).
|
||||
- 저장: project_db 024(urgent_notice*). PROJECT_DB_URL 이 없거나 024 미적용이면 503(화면 스크립트는 조용히 멈춘다).
|
||||
- 핸들러는 동기 DB 라 def(프로젝트 라우터와 같은 이유).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||
|
||||
from . import store
|
||||
|
||||
router = APIRouter(prefix="/notice", tags=["notice"])
|
||||
|
||||
_MIGRATION_MSG = "긴급 공지 기능이 아직 준비되지 않았습니다(project_db 마이그레이션 024 필요)."
|
||||
|
||||
|
||||
def _user(request: Request) -> dict[str, Any]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _is_super(user: dict[str, Any]) -> bool:
|
||||
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
|
||||
|
||||
return str(user.get("email") or "").strip().lower() == SUPER_ADMIN_EMAIL
|
||||
|
||||
|
||||
def _super(request: Request) -> dict[str, Any]:
|
||||
user = _user(request)
|
||||
if not _is_super(user):
|
||||
raise HTTPException(status_code=403, detail="긴급 공지는 수퍼관리자만 만들 수 있습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _store(request: Request) -> Any:
|
||||
st = getattr(request.app.state, "notice_store", None)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||
return st
|
||||
|
||||
|
||||
def _call(fn: Any, **kw: Any) -> Any:
|
||||
try:
|
||||
return fn(**kw)
|
||||
except store.NoticeMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||
|
||||
|
||||
def _public(n: dict[str, Any]) -> dict[str, Any]:
|
||||
"""받는 사람 화면에 보내는 값 — 받는 사람 목록·확인 현황은 빼고."""
|
||||
return {k: n[k] for k in ("id", "title", "body_html", "show_at", "created_by")}
|
||||
|
||||
|
||||
# ── 화면 ─────────────────────────────────────────────────────
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def notice_admin_page(request: Request) -> HTMLResponse:
|
||||
"""긴급 공지 관리 — 수퍼관리자만. 목록(예약·표시 중·취소)·확인 현황·새 공지."""
|
||||
from app.main import build_erp_nav, render_template, user_store # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _super(request)
|
||||
st = getattr(request.app.state, "notice_store", None)
|
||||
enabled = bool(st) and st.enabled()
|
||||
# 받는 사람 후보 = 등록 사용자 전원 — 프로젝트 멤버 고르기와 같은 모양(아이콘 + 이름)으로 그린다(project.js memberPickHtml)
|
||||
people = sorted(
|
||||
({"email": u["email"], "id": u["email"].split("@")[0], "name": u.get("name") or u["email"].split("@")[0],
|
||||
"avatar": u.get("picture") or ""} for u in user_store.list_all()),
|
||||
key=lambda p: p["id"],
|
||||
)
|
||||
return render_template(request, "notice/admin.html", {
|
||||
"user": user, "is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=""),
|
||||
"page_title": "긴급 공지", "page_subtitle": "정한 시각에 받는 사람 화면 가운데에 띄웁니다([확인] 전까지)",
|
||||
"enabled": enabled, "people": people,
|
||||
})
|
||||
|
||||
|
||||
# ── 받는 사람 ────────────────────────────────────────────────
|
||||
@router.get("/api/pending")
|
||||
def api_pending(request: Request) -> JSONResponse:
|
||||
"""지금 내가 봐야 할 공지(띄울 시각이 지났고 아직 [확인] 안 한 것, 오래된 것부터)."""
|
||||
user = _user(request)
|
||||
st = _store(request)
|
||||
rows = _call(st.pending_for, email=user["email"])
|
||||
return JSONResponse({"notices": [_public(n) for n in rows]})
|
||||
|
||||
|
||||
@router.post("/api/{notice_id}/ack")
|
||||
def api_ack(request: Request, notice_id: int) -> JSONResponse:
|
||||
"""[확인] — 받는 사람이고 이미 띄워진(취소 안 된) 공지만. 여러 번 눌러도 한 번 기록."""
|
||||
user = _user(request)
|
||||
st = _store(request)
|
||||
n = _call(st.get_notice, notice_id=notice_id)
|
||||
if n is None or not st.is_recipient(notice=n, email=user["email"]):
|
||||
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||
_call(st.ack, notice_id=notice_id, email=user["email"])
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.get("/images/{image_id}")
|
||||
def notice_image(request: Request, image_id: int) -> Response:
|
||||
"""공지 본문 이미지 — 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난 공지)만."""
|
||||
from datetime import datetime # noqa: WPS433
|
||||
|
||||
from app.timezone import KST # noqa: WPS433
|
||||
|
||||
user = _user(request)
|
||||
st = _store(request)
|
||||
img = _call(st.get_image, image_id=image_id)
|
||||
if img is None:
|
||||
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||
if not _is_super(user):
|
||||
n = _call(st.get_notice, notice_id=int(img["notice_id"])) if img["notice_id"] else None
|
||||
if (n is None or n["cancelled_at"] or not st.is_recipient(notice=n, email=user["email"])
|
||||
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST)):
|
||||
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||
return Response(content=bytes(img["data"]), media_type=img["content_type"], headers={
|
||||
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=3600",
|
||||
"Content-Security-Policy": "default-src 'none'; img-src 'self'; sandbox",
|
||||
})
|
||||
|
||||
|
||||
# ── 수퍼관리자 ───────────────────────────────────────────────
|
||||
@router.get("/api/notices")
|
||||
def api_list(request: Request) -> JSONResponse:
|
||||
_super(request)
|
||||
st = _store(request)
|
||||
return JSONResponse({"notices": _call(st.list_notices)})
|
||||
|
||||
|
||||
def _fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"title": payload.get("title"), "body": payload.get("body_html") or "",
|
||||
"show_at": payload.get("show_at"), "to_all": payload.get("to_all", True),
|
||||
"targets": payload.get("targets") or []}
|
||||
|
||||
|
||||
@router.post("/api/notices")
|
||||
def api_create(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
user = _super(request)
|
||||
st = _store(request)
|
||||
n = _call(st.create_notice, **_fields(payload), by=user["email"])
|
||||
return JSONResponse({"notice": n}, status_code=201)
|
||||
|
||||
|
||||
@router.put("/api/notices/{notice_id}")
|
||||
def api_update(request: Request, notice_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""고치기 — reshow=true 면 이미 [확인]한 사람에게도 다시 띄운다."""
|
||||
user = _super(request)
|
||||
st = _store(request)
|
||||
n = _call(st.update_notice, notice_id=notice_id, **_fields(payload), by=user["email"],
|
||||
reshow=payload.get("reshow") is True)
|
||||
return JSONResponse({"notice": n})
|
||||
|
||||
|
||||
@router.post("/api/notices/{notice_id}/cancel")
|
||||
def api_cancel(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""취소(더 띄우지 않음) {cancel: true} · 되돌리기 {cancel: false}."""
|
||||
user = _super(request)
|
||||
st = _store(request)
|
||||
n = _call(st.cancel_notice, notice_id=notice_id, by=user["email"], cancel=payload.get("cancel", True) is not False)
|
||||
return JSONResponse({"notice": n})
|
||||
|
||||
|
||||
@router.post("/api/images")
|
||||
def api_upload_image(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""본문 이미지 올리기 — 저장(공지 만들기·고치기) 때 본문에 든 것만 그 공지에 묶인다."""
|
||||
user = _super(request)
|
||||
st = _store(request)
|
||||
data = file.file.read(store.IMAGE_MAX_BYTES + 1)
|
||||
img = _call(st.add_image, data=data, filename=file.filename or "image", by=user["email"])
|
||||
return JSONResponse({"image": img}, status_code=201)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""긴급 공지 — 순수 검증(DB 없음). 저장은 db.py, 화면·권한은 router.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.modules.project import store as pj_store
|
||||
from app.timezone import KST
|
||||
|
||||
TITLE_MAX = 200
|
||||
BODY_MAX = 100_000 # 정리한 HTML 기준(이미지는 주소만 들어간다)
|
||||
IMAGE_MAX_BYTES = 10 * 1024 * 1024
|
||||
TARGETS_MAX = 500
|
||||
|
||||
# 이미지 형식은 올린 쪽이 정한 Content-Type 이 아니라 파일 앞 바이트로 정한다(svg·html 은 받지 않는다).
|
||||
_MAGIC: tuple[tuple[bytes, str], ...] = (
|
||||
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
||||
(b"\xff\xd8\xff", "image/jpeg"),
|
||||
(b"GIF87a", "image/gif"),
|
||||
(b"GIF89a", "image/gif"),
|
||||
)
|
||||
_IMG_SRC_OK = re.compile(r"^/notice/images/(\d+)$")
|
||||
_IMG_TAG = re.compile(r"<img\b[^>]*>", re.IGNORECASE)
|
||||
_SRC_ATTR = re.compile(r"""\bsrc\s*=\s*"([^"]*)\"""", re.IGNORECASE)
|
||||
|
||||
|
||||
class NoticeMigrationNeeded(Exception):
|
||||
"""project_db 024 미적용."""
|
||||
|
||||
|
||||
def validate_title(v: Any) -> str:
|
||||
t = pj_store.norm_str(v)
|
||||
if not t:
|
||||
raise ValueError("공지 제목을 입력하세요.")
|
||||
if len(t) > TITLE_MAX:
|
||||
raise ValueError(f"제목은 {TITLE_MAX}자 이하로 입력하세요.")
|
||||
return t
|
||||
|
||||
|
||||
def sanitize_body(html: Any) -> str:
|
||||
"""작업 설명란과 같은 허용 목록으로 정리한 뒤, 이미지는 공지 이미지 주소(/notice/images/{id})만 남긴다
|
||||
(외부 주소·data: 이미지는 뺀다 — 받는 사람 화면에서 다른 곳으로 요청이 나가지 않게)."""
|
||||
out = pj_store.sanitize_description_html(str(html or ""))
|
||||
|
||||
def keep(m: re.Match[str]) -> str:
|
||||
src = _SRC_ATTR.search(m.group(0))
|
||||
return m.group(0) if src and _IMG_SRC_OK.match(src.group(1)) else ""
|
||||
out = _IMG_TAG.sub(keep, out)
|
||||
if len(out) > BODY_MAX:
|
||||
raise ValueError("내용이 너무 깁니다.")
|
||||
return out
|
||||
|
||||
|
||||
def image_ids_in(html: str) -> list[int]:
|
||||
"""본문에 들어 있는 공지 이미지 id(순서대로, 중복 없이)."""
|
||||
ids: list[int] = []
|
||||
for tag in _IMG_TAG.findall(html or ""):
|
||||
src = _SRC_ATTR.search(tag)
|
||||
m = _IMG_SRC_OK.match(src.group(1)) if src else None
|
||||
if m and int(m.group(1)) not in ids:
|
||||
ids.append(int(m.group(1)))
|
||||
return ids
|
||||
|
||||
|
||||
def parse_show_at(v: Any, *, now: datetime | None = None) -> datetime:
|
||||
"""띄울 시각 — 'YYYY-MM-DDTHH:MM'(화면 입력, 한국시간) 또는 시간대가 붙은 ISO. 비우면 지금."""
|
||||
s = pj_store.norm_str(v)
|
||||
if not s:
|
||||
return now or datetime.now(KST)
|
||||
try:
|
||||
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||
if d.tzinfo is None:
|
||||
d = d.replace(tzinfo=KST)
|
||||
if not 2000 <= d.year <= 2100:
|
||||
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||
return d
|
||||
|
||||
|
||||
def validate_targets(to_all: Any, targets: Any) -> tuple[bool, list[str]]:
|
||||
"""(전체 여부, 받는 사람 이메일). 전체가 아니면 한 명 이상."""
|
||||
if to_all is True or to_all in ("1", "true", "on"):
|
||||
return True, []
|
||||
emails = pj_store.normalize_emails(targets if isinstance(targets, (list, tuple)) else [])
|
||||
if not emails:
|
||||
raise ValueError("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요.")
|
||||
if len(emails) > TARGETS_MAX:
|
||||
raise ValueError(f"받는 사람은 {TARGETS_MAX}명까지 고를 수 있습니다.")
|
||||
return False, emails
|
||||
|
||||
|
||||
def sniff_image(data: bytes) -> str:
|
||||
"""파일 앞 바이트로 이미지 형식 — png·jpeg·gif·webp 만. 아니면 ValueError."""
|
||||
if not data:
|
||||
raise ValueError("빈 파일입니다.")
|
||||
if len(data) > IMAGE_MAX_BYTES:
|
||||
raise ValueError("이미지는 10MB 이하만 올릴 수 있습니다.")
|
||||
for magic, ctype in _MAGIC:
|
||||
if data.startswith(magic):
|
||||
return ctype
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
raise ValueError("이미지(png·jpg·gif·webp)만 올릴 수 있습니다.")
|
||||
@@ -0,0 +1,70 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261013i" />
|
||||
<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 %}
|
||||
|
||||
{% block content %}
|
||||
{% if not enabled %}
|
||||
<div class="ntc-card">
|
||||
<h2>긴급 공지 준비 필요</h2>
|
||||
<p>project_db 마이그레이션 024(<code>scripts/sql/project_db_024_urgent_notices.sql</code>)를 적용하면 사용할 수 있습니다.</p>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="ntc-wrap" id="ntc-root">
|
||||
<section class="ntc-card" aria-labelledby="ntc-form-title">
|
||||
<h2 id="ntc-form-title">새 긴급 공지</h2>
|
||||
<input type="hidden" id="ntc-id" value="" />
|
||||
<label class="ntc-field">제목
|
||||
<input type="text" id="ntc-title" maxlength="200" placeholder="예: 오늘 18시 서버 점검" autocomplete="off" />
|
||||
</label>
|
||||
{# 내용 — 작업 설명란과 같은 편집기(서식 도구 전체·이미지 붙여넣기/버튼·크기 조절·링크·체크리스트) #}
|
||||
<div class="ntc-field pj-desc-block ntc-desc">
|
||||
<div class="pj-desc-toolbar"><span>내용</span><span class="pj-muted-sm" id="ntc-hint"></span></div>
|
||||
{% with fmtbar_id = "ntc-fmtbar", img_input_id = "ntc-img-input" %}{% include "project/_desc_fmtbar.html" %}{% endwith %}
|
||||
<div class="pj-desc-wrap">
|
||||
<div class="pj-desc-editor" id="ntc-body" contenteditable="true" role="textbox" aria-multiline="true" aria-label="공지 내용"
|
||||
data-placeholder="공지 내용을 쓰세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||
</div>
|
||||
</div>
|
||||
{# 띄울 날짜 — 프로젝트와 같은 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸. 둘 다 비우면 바로 #}
|
||||
<div class="ntc-field">띄울 시각 <small class="ntc-sub">한국시간 · 날짜를 비우면 바로</small>
|
||||
<div class="ntc-when">
|
||||
<input type="date" id="ntc-date" />
|
||||
<input type="time" id="ntc-time" class="ntc-time" step="300" aria-label="띄울 시각" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="ntc-field">받는 사람
|
||||
<div class="ntc-targets">
|
||||
<div class="ntc-to">
|
||||
<label><input type="radio" name="ntc-to" value="all" checked /> 전체(로그인하는 모든 사람)</label>
|
||||
<label><input type="radio" name="ntc-to" value="some" /> 고른 사람만</label>
|
||||
</div>
|
||||
{# 프로젝트 멤버 고르기와 같은 모양 — 아이콘 + 이름 + 체크 #}
|
||||
<div class="pj-member-picker ntc-people" id="ntc-people" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<label class="ntc-field ntc-inline" id="ntc-reshow-row" hidden>
|
||||
<input type="checkbox" id="ntc-reshow" /> 이미 [확인]한 사람에게도 다시 띄우기
|
||||
</label>
|
||||
<div class="ntc-actions">
|
||||
<button type="button" class="pj-btn" id="ntc-reset">새로 쓰기</button>
|
||||
<button type="button" class="pj-btn" id="ntc-preview">미리 보기</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="ntc-save">공지 만들기</button>
|
||||
</div>
|
||||
<p class="ntc-msg" id="ntc-msg" role="alert" hidden></p>
|
||||
</section>
|
||||
|
||||
<section class="ntc-card" aria-labelledby="ntc-list-title">
|
||||
<h2 id="ntc-list-title">공지 목록</h2>
|
||||
<div class="ntc-list" id="ntc-list">불러오는 중…</div>
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261013i" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,503 @@
|
||||
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
||||
|
||||
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||||
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||||
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
|
||||
|
||||
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
||||
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
||||
규칙(2026-10-14 사용자 확인): **1열에 날짜가 있는 줄의 19열 값**을 가져온다 — 19열이 빈 줄은 건너뛰고(윙 보고서는
|
||||
캠페인 줄에도 날짜가 있고 19열이 비어 있다), 같은 날짜에 값이 있는 줄이 여럿이면 더한다.
|
||||
1열이 빈 캠페인 줄·맨 위 "전체" 합계 줄은 건너뛴다. 날짜는 있는데 19열 값이 한 줄도 없는 날은 empty_days 로 알려 준다.
|
||||
네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
|
||||
1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
|
||||
나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
|
||||
화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
|
||||
|
||||
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Callable, Mapping, Sequence
|
||||
|
||||
from . import calc
|
||||
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||
|
||||
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||
CHANNELS: tuple[tuple[str, str], ...] = (
|
||||
("google", "구글"),
|
||||
("meta", "메타"),
|
||||
("naver", "네이버"),
|
||||
("coupang_wing", "쿠팡(윙)"),
|
||||
("coupang_rocket", "쿠팡(로켓)"),
|
||||
("ohouse", "오늘의집"),
|
||||
("gmarket", "G마켓"),
|
||||
("kakao", "카카오"),
|
||||
("gsshop", "GS샵"),
|
||||
("elevenst", "11번가"),
|
||||
("lotteon", "롯데ON"),
|
||||
("toss", "토스"),
|
||||
("atomy", "애터미아자몰"),
|
||||
)
|
||||
CHANNEL_NAMES = dict(CHANNELS)
|
||||
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
||||
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
|
||||
# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
|
||||
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
||||
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
||||
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||||
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
|
||||
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
||||
|
||||
|
||||
def roas(sales: int, spend: int) -> int | None:
|
||||
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
|
||||
if not spend or spend <= 0:
|
||||
return None
|
||||
return int((Decimal(int(sales)) * 100 / Decimal(int(spend))).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def roas_basis(code: str) -> str:
|
||||
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
|
||||
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
|
||||
|
||||
|
||||
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
|
||||
s: date, e: date) -> int | None:
|
||||
"""보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
|
||||
rev = Decimal(0)
|
||||
spend = 0
|
||||
for (d, c), r in file_roas_map.items():
|
||||
if c != code or not s <= d <= e or r is None:
|
||||
continue
|
||||
amt = int(spends.get((d, c)) or 0)
|
||||
if amt > 0:
|
||||
rev += Decimal(str(r)) * amt
|
||||
spend += amt
|
||||
if spend <= 0:
|
||||
return None
|
||||
return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
|
||||
file_of: Callable[[str], int | None] | None = None) -> int | None:
|
||||
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
|
||||
if code in FILE_ROAS:
|
||||
return file_of(code) if file_of else None
|
||||
mcode = ROAS_SALES_CODE.get(code)
|
||||
return None if mcode is None else roas(sales_of(mcode), spend)
|
||||
|
||||
ROCKET_DATE_COL = 0 # 1열 날짜
|
||||
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
||||
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
|
||||
|
||||
|
||||
NAVER_DATE_COL = 2 # 3열 기간(날짜)
|
||||
NAVER_AMOUNT_COL = 3 # 4열 총비용
|
||||
NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
|
||||
NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
|
||||
|
||||
|
||||
class AdMigrationNeeded(Exception):
|
||||
"""광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParseResult:
|
||||
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
|
||||
# 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
|
||||
roas: dict[date, Decimal] = field(default_factory=dict)
|
||||
metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
|
||||
columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
|
||||
empty_days: list[date] = field(default_factory=list) # 날짜 줄은 있는데 금액이 한 줄도 없던 날(저장 안 함)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 파일 읽기
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _decode_csv(content: bytes) -> str:
|
||||
for enc in ("utf-8-sig", "cp949"):
|
||||
try:
|
||||
return content.decode(enc)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).")
|
||||
|
||||
|
||||
def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]:
|
||||
"""CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로)."""
|
||||
if not content:
|
||||
raise UploadError("빈 파일입니다.")
|
||||
if len(content) > MAX_FILE_BYTES:
|
||||
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||
is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx")
|
||||
if not is_xlsx:
|
||||
return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))]
|
||||
try:
|
||||
import openpyxl # noqa: WPS433
|
||||
|
||||
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||
raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None
|
||||
try:
|
||||
return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)]
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||||
"""쿠팡(윙·로켓) 광고 보고서 → (날짜, 그날 19열 청구금액(+부가가치세) 합). 1열에 날짜가 있고 19열에 값이 있는 줄만,
|
||||
같은 날짜는 더한다. 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
|
||||
rows = read_rows(content, filename)
|
||||
res = ParseResult()
|
||||
sums: dict[date, int] = {}
|
||||
dated: set[date] = set()
|
||||
for r, row in enumerate(rows, start=1):
|
||||
raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_DATE_COL else None
|
||||
text = str(raw_day or "").strip()
|
||||
if not text or text.replace(" ", "") in SKIP_LABELS:
|
||||
res.skipped += 1
|
||||
continue
|
||||
try:
|
||||
day = parse_date(raw_day)
|
||||
except ValueError:
|
||||
if r == 1: # 머리글
|
||||
res.skipped += 1
|
||||
continue
|
||||
res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||||
continue
|
||||
if day is None:
|
||||
res.skipped += 1
|
||||
continue
|
||||
raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None
|
||||
try:
|
||||
amt = parse_amount(raw_amt)
|
||||
except ValueError:
|
||||
res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).")
|
||||
continue
|
||||
dated.add(day)
|
||||
if amt is None:
|
||||
res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀
|
||||
elif abs(amt) > MAX_AMOUNT:
|
||||
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
|
||||
elif day > today:
|
||||
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||
else:
|
||||
sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다
|
||||
if len(sums) > MAX_DATA_ROWS:
|
||||
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||
if len(res.errors) > MAX_ERRORS:
|
||||
break
|
||||
res.entries = sorted(sums.items())
|
||||
res.empty_days = sorted(d for d in dated if d not in sums and d <= today)
|
||||
# 날짜 줄은 있는데 청구금액이 한 줄도 없는 파일(그 달 광고비 0 등)은 오류가 아니라 넘어간다(2026-10-14 사용자 요청).
|
||||
# 날짜 줄 자체가 없을 때만 양식 오류.
|
||||
if not dated and not res.errors:
|
||||
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
|
||||
return res
|
||||
|
||||
|
||||
def _number(value: Any) -> Decimal | None:
|
||||
"""숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
raise ValueError
|
||||
text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
|
||||
try:
|
||||
num = Decimal(text)
|
||||
except InvalidOperation:
|
||||
raise ValueError from None
|
||||
if not num.is_finite():
|
||||
raise ValueError
|
||||
return num
|
||||
|
||||
|
||||
def _json_num(num: Decimal | None) -> Any:
|
||||
if num is None:
|
||||
return None
|
||||
return int(num) if num == num.to_integral_value() else float(round(num, 2))
|
||||
|
||||
|
||||
def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||||
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(12열) + 나머지 항목. 잘못된 줄이 있으면 errors."""
|
||||
rows = read_rows(content, filename)
|
||||
res = ParseResult()
|
||||
header: tuple[Any, ...] = ()
|
||||
seen: dict[date, int] = {}
|
||||
for r, row in enumerate(rows, start=1):
|
||||
raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_DATE_COL else None
|
||||
text = str(raw_day or "").strip()
|
||||
if not text or text.replace(" ", "") in SKIP_LABELS:
|
||||
res.skipped += 1
|
||||
continue
|
||||
try:
|
||||
day = parse_date(raw_day)
|
||||
except ValueError:
|
||||
if not header: # 머리글(1행 "기간")
|
||||
header = tuple(str(h or "").strip() for h in row)
|
||||
res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
|
||||
res.skipped += 1
|
||||
continue
|
||||
res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||||
continue
|
||||
if day is None:
|
||||
res.skipped += 1
|
||||
continue
|
||||
try:
|
||||
amt = parse_amount(row[NAVER_AMOUNT_COL] if len(row) > NAVER_AMOUNT_COL else None)
|
||||
except ValueError:
|
||||
res.errors.append(f"{r}행 4열: 총비용이 숫자가 아닙니다.")
|
||||
continue
|
||||
try:
|
||||
ro = _number(row[NAVER_ROAS_COL] if len(row) > NAVER_ROAS_COL else None)
|
||||
except ValueError:
|
||||
res.errors.append(f"{r}행 12열: 광고수익률(ROAS)이 숫자가 아닙니다.")
|
||||
continue
|
||||
if amt is None:
|
||||
res.errors.append(f"{r}행 4열: {day.isoformat()} 총비용이 비어 있습니다.")
|
||||
elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
|
||||
res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
|
||||
elif day > today:
|
||||
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||
elif day in seen:
|
||||
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
|
||||
else:
|
||||
seen[day] = r
|
||||
res.entries.append((day, amt))
|
||||
if ro is not None:
|
||||
res.roas[day] = ro
|
||||
m: dict[str, Any] = {}
|
||||
for i, v in enumerate(row):
|
||||
name = header[i] if i < len(header) else f"{i + 1}열"
|
||||
if i in NAVER_SKIP_COLS or not name:
|
||||
continue
|
||||
try:
|
||||
m[name] = _json_num(_number(v))
|
||||
except ValueError:
|
||||
m[name] = str(v)[:100]
|
||||
res.metrics[day] = m
|
||||
if len(res.entries) > MAX_DATA_ROWS:
|
||||
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||
if len(res.errors) > MAX_ERRORS:
|
||||
break
|
||||
if not res.entries and not res.errors:
|
||||
raise UploadError("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
|
||||
return res
|
||||
|
||||
|
||||
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
|
||||
PARSERS: dict[str, Callable[..., ParseResult]] = {
|
||||
"naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
|
||||
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
|
||||
UPLOAD_HELP = {
|
||||
"naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
|
||||
"나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
|
||||
"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
|
||||
MAX_UPLOAD_FILES = 30
|
||||
|
||||
|
||||
def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseResult, list[date]]:
|
||||
"""여러 파일(이름, 파일 수정 시각, 읽은 결과)을 하나로 — 같은 날짜가 여러 파일에 있으면 **파일 날짜(수정 시각)가 최신인
|
||||
파일** 값(같으면 나중에 올린 파일). 돌려주는 값: (합친 결과, 여러 파일에 겹친 날짜). 오류는 파일 이름을 앞에 붙여 모은다."""
|
||||
merged = ParseResult()
|
||||
owner: dict[date, tuple[float, int]] = {}
|
||||
overlap: set[date] = set()
|
||||
empty: set[date] = set()
|
||||
for idx, (name, modified, res) in enumerate(parsed):
|
||||
merged.errors.extend(f"[{name}] {e}" for e in res.errors)
|
||||
empty.update(res.empty_days)
|
||||
merged.skipped += res.skipped
|
||||
for c in res.columns:
|
||||
if c not in merged.columns:
|
||||
merged.columns.append(c)
|
||||
picked: dict[date, tuple[int, int]] = {}
|
||||
for idx, (name, modified, res) in enumerate(parsed):
|
||||
for day, amt in res.entries:
|
||||
key = (float(modified or 0), idx)
|
||||
if day in owner:
|
||||
overlap.add(day)
|
||||
if key < owner[day]:
|
||||
continue
|
||||
owner[day] = key
|
||||
picked[day] = (idx, amt)
|
||||
for day in sorted(picked):
|
||||
idx, amt = picked[day]
|
||||
res = parsed[idx][2]
|
||||
merged.entries.append((day, amt))
|
||||
if day in res.roas:
|
||||
merged.roas[day] = res.roas[day]
|
||||
if day in res.metrics:
|
||||
merged.metrics[day] = res.metrics[day]
|
||||
merged.empty_days = sorted(d for d in empty if d not in picked) # 어느 파일에도 값이 없던 날
|
||||
return merged, sorted(overlap)
|
||||
|
||||
|
||||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널)
|
||||
DETAIL_CHANNELS = frozenset({"naver"})
|
||||
|
||||
|
||||
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
|
||||
열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
|
||||
cols: list[str] = []
|
||||
for r in rows:
|
||||
for k in (r.get("metrics") or {}):
|
||||
if k not in cols:
|
||||
cols.append(k)
|
||||
sums: dict[str, Decimal] = {}
|
||||
for r in rows:
|
||||
for k, v in (r.get("metrics") or {}).items():
|
||||
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
||||
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
|
||||
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
|
||||
for k in cols:
|
||||
if "클릭률" in k and sums.get("노출수"):
|
||||
total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
|
||||
elif ("수익률" in k or "ROAS" in k.upper()):
|
||||
spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||||
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
|
||||
if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||||
total[k] = float(round(rev / spend, 2)) if spend else None
|
||||
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
|
||||
"roas": float(r["roas"]) if r.get("roas") is not None else None,
|
||||
"values": r.get("metrics") or {}} for r in rows]
|
||||
return {"columns": cols, "rows": out_rows, "total": total}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면 데이터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
holidays: Mapping[str, str] | None = None,
|
||||
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
|
||||
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
|
||||
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
|
||||
codes = list(CHANNEL_CODES)
|
||||
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||
ref = period.end if period.end < today else today if period.start <= today else period.start
|
||||
month_period = calc.resolve_period("month", ref)
|
||||
year_period = calc.resolve_period("year", ref)
|
||||
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
|
||||
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
|
||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||
q_end = max(period.end, year_period.end)
|
||||
|
||||
migration_needed = False
|
||||
try:
|
||||
amounts, sources = store.ad_amounts(q_start, q_end)
|
||||
except AdMigrationNeeded:
|
||||
amounts, sources, migration_needed = {}, {}, True
|
||||
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
|
||||
roas_reader = getattr(store, "ad_roas", None)
|
||||
try:
|
||||
roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
|
||||
except AdMigrationNeeded:
|
||||
roas_map = {}
|
||||
|
||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
|
||||
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
|
||||
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
|
||||
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
||||
|
||||
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
|
||||
total_codes = list(sales_codes)
|
||||
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
|
||||
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
|
||||
|
||||
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
|
||||
want = set(mcodes)
|
||||
return sum(v for (d, c), v in sales.items() if c in want and s <= d <= e)
|
||||
|
||||
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
|
||||
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||
|
||||
word = {"day": "오늘" if period.start == today else "해당일",
|
||||
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
kpis = [
|
||||
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
||||
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
|
||||
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
|
||||
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||
]
|
||||
|
||||
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if k == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||
|
||||
if period.kind == "custom":
|
||||
from datetime import timedelta # noqa: WPS433
|
||||
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||
nav = {"prev": prev_url, "next": next_url, "quick": [
|
||||
{"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today},
|
||||
{"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end},
|
||||
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||
]}
|
||||
|
||||
share = calc.by_code(cells, codes, period.start, period.end)
|
||||
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||
# 칸마다 ROAS — "광고비(ROAS%)" 로 보인다. 행 기간 = 그 날·주·월(합계 행은 선택 기간)
|
||||
for row in table:
|
||||
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
|
||||
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
|
||||
row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
|
||||
lambda f: file_roas(f, roas_map, amounts, s, e)) for c in codes}
|
||||
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
|
||||
m_s, m_e = month_period.start, month_period.end
|
||||
for r in month["rows"]:
|
||||
r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
|
||||
lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
|
||||
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
|
||||
year = calc.year_months(year_period.start.year, codes, cells, today=today)
|
||||
for i, r in enumerate(year["rows"], start=1):
|
||||
s = date(year_period.start.year, i, 1)
|
||||
r["roas"] = None if r.get("future") or not total_codes else roas(sales_sum(total_codes, s, calc.month_end(s)), r["gross"] or 0)
|
||||
year["total"]["roas"] = roas(sales_sum(total_codes, year_period.start, year_period.end), year["total"]["gross"]) if total_codes else None
|
||||
return {
|
||||
"nav": nav,
|
||||
"period": period,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"codes": codes,
|
||||
"names": dict(CHANNEL_NAMES),
|
||||
"kpis": kpis,
|
||||
"table": table,
|
||||
"month": month,
|
||||
"year": year,
|
||||
"roas_basis": {c: roas_basis(c) for c in codes},
|
||||
"detail_channels": sorted(DETAIL_CHANNELS),
|
||||
"chart_daily": calc.daily_series(period, codes, cells),
|
||||
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
|
||||
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
||||
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||
if s == "upload" and period.start <= d <= period.end),
|
||||
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||||
"migration_needed": migration_needed,
|
||||
}
|
||||
@@ -33,6 +33,7 @@ STATUS_LABELS: dict[str, str] = {
|
||||
"unknown": "확인 전",
|
||||
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
||||
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
||||
"manual": "수동 입력", # 화면 전용 — API 없이 수동 입력만 쓰는 쇼핑몰(manual_only)
|
||||
}
|
||||
|
||||
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
||||
@@ -175,6 +176,8 @@ class MarketplaceAdapter(ABC):
|
||||
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
|
||||
docs_url: str = ""
|
||||
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
|
||||
# True 면 API 연동이 없는 수동 입력 전용 쇼핑몰 — 매출 업데이트에서 빠지고, 인증 설정·연결 테스트가 없다.
|
||||
manual_only: bool = False
|
||||
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
|
||||
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
|
||||
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
|
||||
|
||||
@@ -8,12 +8,23 @@
|
||||
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
||||
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
||||
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
||||
연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
|
||||
|
||||
매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
|
||||
· 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
|
||||
· 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
|
||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
|
||||
매출 수집 — 맞출 화면: WING → 비즈니스 인사이트 → **판매분석**(판매자배송 + 로켓그로스, 날짜 선택) 의 "매출(원)"
|
||||
(2026-10-12 사용자 지정). 판매분석 자체를 주는 Open API 는 없다(2026-10-12 developers.coupang.com API 목록 확인) —
|
||||
그래서 주문 API 두 개를 결제일(한국 시간)로 합친다:
|
||||
- 판매자배송: 발주서 목록(일단위 페이징) GET /v2/providers/openapi/apis/api/v5/vendors/{vendorId}/ordersheets
|
||||
?createdAtFrom=yyyy-mm-dd+09:00&createdAtTo=…&status=…&maxPerPage=50&nextToken=
|
||||
— 주문일 기준·한 번에 31일까지·상태(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING)마다 따로.
|
||||
결제일(paidAt)로 다시 거른다(주문일 하루 앞부터 조회). 줄 금액 = orderPrice(판매가 × 수량, 쿠폰 할인 전).
|
||||
완료된 반품·결제 전 취소된 발주서는 이 목록에 없다(쿠팡 안내).
|
||||
- 로켓그로스: 주문 목록 GET /v2/providers/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders
|
||||
?paidDateFrom=yyyymmdd&paidDateTo=yyyymmdd&nextToken= — 결제일 기준·30일까지·분당 50회.
|
||||
줄 금액 = unitSalesPrice × salesQuantity. 쿠팡 안내상 **출고된 주문만** 나온다(오늘 주문은 출고 뒤에 잡힐 수 있음).
|
||||
- SALE = 주문 하나(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), 날짜 = 결제일.
|
||||
결제 뒤 취소된 줄(canceled·cancelCount)도 결제일 매출에 둔다(지난 날짜가 나중에 줄지 않게) — 금액은 참고로 따로.
|
||||
판매분석 "매출" 의 정확한 정의(할인 전·후, 취소 포함 여부)는 공개 문서가 없어 **설정 → 쇼핑몰 원본 데이터 확인**
|
||||
(reconcile)의 날짜별 후보 금액을 WING 숫자와 비교해 확정한다. 구매자 이름·연락처·주소는 저장·표시하지 않는다.
|
||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 여기에 넣지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,19 +32,47 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
from typing import Any
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any, Iterable
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
)
|
||||
from .naver import field_summary, flatten
|
||||
|
||||
HOST = "https://api-gateway.coupang.com"
|
||||
ORDERS_PATH = "/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets"
|
||||
RG_ORDERS_PATH = "/v2/providers/rg_open_api/apis/api/v1/vendors/{vendor}/rg/orders"
|
||||
EVENT_PREFIX = "coupang:"
|
||||
RG_PREFIX = "coupang:rg:"
|
||||
STATUSES = ("ACCEPT", "INSTRUCT", "DEPARTURE", "DELIVERING", "FINAL_DELIVERY", "NONE_TRACKING")
|
||||
STATUS_KO = {"ACCEPT": "결제완료", "INSTRUCT": "상품준비중", "DEPARTURE": "배송지시", "DELIVERING": "배송중",
|
||||
"FINAL_DELIVERY": "배송완료", "NONE_TRACKING": "업체직송", "RG": "로켓그로스"}
|
||||
ORDER_SPAN_DAYS = 31 # 발주서 목록 한 번에 조회할 수 있는 기간(시작·끝 포함)
|
||||
RG_SPAN_DAYS = 30 # 로켓그로스 주문 목록 한 번에 조회할 수 있는 기간
|
||||
PAGE_SIZE = 50
|
||||
MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
|
||||
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
|
||||
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
|
||||
RETRY_429 = 3
|
||||
RETRY_TIMEOUT_1DAY = 2 # 하루 구간도 시간 초과면 잠깐 쉬고 다시 부르는 횟수
|
||||
PROBE_MAX_DAYS = 31
|
||||
KST_OFFSET = timedelta(hours=9)
|
||||
|
||||
|
||||
class GatewayTimeout(ApiError):
|
||||
"""쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다."""
|
||||
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||
|
||||
|
||||
def signed_date(now: float | None = None) -> str:
|
||||
@@ -54,14 +93,163 @@ def build_query(params: dict[str, Any]) -> str:
|
||||
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
"""금액 → 원 정수. 쿠팡 Money({"units": 15000, "nanos": 0})·숫자·문자열("27800") 모두."""
|
||||
if isinstance(value, dict):
|
||||
return _won(value.get("units")) + int(round((_num(value.get("nanos")) or 0) / 1e9))
|
||||
n = _num(value)
|
||||
return int(round(n)) if n is not None else 0
|
||||
|
||||
|
||||
def _num(value: Any) -> float | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
return float(str(value).replace(",", "").strip() or 0)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _kst_day(value: Any) -> date | None:
|
||||
"""결제 시각 → 한국 날짜. ISO 문자열("2025-08-01T10:06:12+09:00", 시간대 없으면 한국 시간) 또는
|
||||
밀리초 타임스탬프(1746093162000, 로켓그로스)."""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
n = _num(value) if not isinstance(value, str) or value.strip().isdigit() else None
|
||||
if n is not None:
|
||||
secs = n / 1000 if n > 1e11 else n
|
||||
return (datetime.fromtimestamp(secs, tz=timezone.utc) + KST_OFFSET).date()
|
||||
s = str(value).strip().replace("Z", "+00:00")
|
||||
try:
|
||||
dt = datetime.fromisoformat(s if "T" in s or " " in s else s[:10])
|
||||
except ValueError:
|
||||
try:
|
||||
return date.fromisoformat(s[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
dt = (dt - dt.utcoffset()).replace(tzinfo=None) + KST_OFFSET # type: ignore[operator]
|
||||
return dt.date()
|
||||
|
||||
|
||||
def spans(start: date, end: date, days: int) -> list[tuple[date, date]]:
|
||||
"""[start, end] 를 days 일(시작·끝 포함) 이하 구간으로 자른다."""
|
||||
out, d = [], start
|
||||
while d <= end:
|
||||
e = min(end, d + timedelta(days=days - 1))
|
||||
out.append((d, e))
|
||||
d = e + timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def safe_order(o: dict[str, Any]) -> dict[str, Any]:
|
||||
"""개인정보 항목을 뺀 발주서(원본 확인·저장용)."""
|
||||
out = {k: v for k, v in o.items() if k not in PERSONAL_KEYS}
|
||||
if isinstance(out.get("orderItems"), list):
|
||||
out["orderItems"] = [{k: v for k, v in it.items() if k not in PERSONAL_ITEM_KEYS}
|
||||
for it in out["orderItems"] if isinstance(it, dict)]
|
||||
return out
|
||||
|
||||
|
||||
def line_records(o: dict[str, Any]) -> list[dict[str, str]]:
|
||||
"""발주서 하나 → 줄(orderItems)마다 평평한 기록 하나 — 원본 확인 표의 항목별 합계용."""
|
||||
base = flatten({k: v for k, v in safe_order(o).items() if k != "orderItems"})
|
||||
items = safe_order(o).get("orderItems") or [{}]
|
||||
return [{**base, **flatten(it, "orderItems")} for it in items]
|
||||
|
||||
|
||||
def seller_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""판매자배송 발주서 → 결제일이 [start, end] 인 줄. 같은 발주서가 두 번 와도(상태 사이 이동) 한 번만."""
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
out: list[dict[str, Any]] = []
|
||||
for o in orders:
|
||||
oid = str(o.get("orderId") or "")
|
||||
day = _kst_day(o.get("paidAt") or o.get("orderedAt"))
|
||||
if not oid or day is None or not (start <= day <= end):
|
||||
continue
|
||||
box = str(o.get("shipmentBoxId") or "")
|
||||
first = len(out)
|
||||
for it in o.get("orderItems") or []:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = (oid, box, str(it.get("vendorItemId") or ""), str(it.get("sequenceNo") or ""))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
qty = _won(it.get("shippingCount"))
|
||||
price = _won(it.get("orderPrice")) or _won(it.get("salesPrice")) * qty
|
||||
cancel_qty = _won(it.get("cancelCount")) + _won(it.get("holdCountForCancel"))
|
||||
canceled = bool(it.get("canceled")) or (qty > 0 and cancel_qty >= qty)
|
||||
cancel_amt = price if canceled else (_won(it.get("salesPrice")) * min(cancel_qty, qty) if cancel_qty else 0)
|
||||
out.append({
|
||||
"orderId": oid, "_day": day, "order_day": _kst_day(o.get("orderedAt")), "status": str(o.get("status") or ""),
|
||||
"amount": price, "discount": _won(it.get("discountPrice")), "canceled": cancel_amt, "qty": qty,
|
||||
"name": str(it.get("sellerProductName") or it.get("vendorItemName") or ""),
|
||||
"opt": str(it.get("sellerProductItemName") or ""), "ship": 0,
|
||||
})
|
||||
# 배송비는 발주서(묶음 배송)마다 한 번 — 그 발주서의 첫 새 줄에(참고용, 매출 제외). 같은 발주서가 또 오면 새 줄이 없어 안 더함
|
||||
if len(out) > first:
|
||||
out[first]["ship"] += _won(o.get("shippingPrice")) + _won(o.get("remotePrice"))
|
||||
return out
|
||||
|
||||
|
||||
def rg_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""로켓그로스 주문 → 결제일이 [start, end] 인 줄. 금액 = 단가 × 수량."""
|
||||
seen: set[tuple[str, str, int]] = set()
|
||||
out: list[dict[str, Any]] = []
|
||||
for o in orders:
|
||||
oid = str(o.get("orderId") or "")
|
||||
day = _kst_day(o.get("paidAt"))
|
||||
if not oid or day is None or not (start <= day <= end):
|
||||
continue
|
||||
for i, it in enumerate(o.get("orderItems") or []):
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = (oid, str(it.get("vendorItemId") or ""), i)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
qty = _won(it.get("salesQuantity"))
|
||||
out.append({"orderId": oid, "_day": day, "order_day": day, "status": "RG",
|
||||
"amount": _won(it.get("unitSalesPrice")) * qty, "discount": 0, "canceled": 0, "qty": qty,
|
||||
"name": str(it.get("productName") or ""), "opt": "", "ship": 0})
|
||||
return out
|
||||
|
||||
|
||||
def group_lines(lines: Iterable[dict[str, Any]], prefix: str) -> dict[str, dict[str, Any]]:
|
||||
"""줄 → 주문 하나(외부 사건 ID 기준)."""
|
||||
orders: dict[str, dict[str, Any]] = {}
|
||||
for ln in lines:
|
||||
eid = f"{prefix}{ln['orderId']}"
|
||||
o = orders.setdefault(eid, {"event_id": eid, "orderId": ln["orderId"], "_day": ln["_day"],
|
||||
"order_day": ln.get("order_day"), "amount": 0, "discount": 0, "canceled": 0,
|
||||
"ship": 0, "qty": 0, "names": [], "opt": "", "statuses": []})
|
||||
for k in ("amount", "discount", "canceled", "ship", "qty"):
|
||||
o[k] += int(ln.get(k) or 0)
|
||||
if ln["name"] and ln["name"] not in o["names"]:
|
||||
o["names"].append(ln["name"])
|
||||
o["opt"] = o["opt"] or ln.get("opt") or ""
|
||||
if ln["status"] and ln["status"] not in o["statuses"]:
|
||||
o["statuses"].append(ln["status"])
|
||||
return orders
|
||||
|
||||
|
||||
class CoupangAdapter(MarketplaceAdapter):
|
||||
code = "coupang"
|
||||
name = "쿠팡"
|
||||
name = "쿠팡(윙)"
|
||||
auth_type = "api_key"
|
||||
docs_url = "https://developers.coupangcorp.com/"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://developers.coupang.com/"
|
||||
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
||||
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
|
||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인). 매출은 판매자배송 + 로켓그로스 주문을 "
|
||||
"결제일로 합칩니다(WING 비즈니스 인사이트 → 판매분석 '매출'과 비교).")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_call = 0.0
|
||||
self._last_rg_call = 0.0
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
@@ -71,42 +259,253 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
]
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
def _vendor(self, ctx: AdapterContext) -> str:
|
||||
v = ctx.credentials.get("vendor_id").strip()
|
||||
if not v:
|
||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||
return v
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> dict[str, Any]:
|
||||
"""GET — 호출 간격 유지(로켓그로스는 분당 50회), 429 는 잠깐 쉬고 다시."""
|
||||
import httpx # 지연 import
|
||||
|
||||
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
||||
if not (access and secret):
|
||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||
query = build_query(params)
|
||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||
"Content-Type": "application/json;charset=UTF-8"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
|
||||
if res.status_code in (401, 403):
|
||||
raise AuthFailed(
|
||||
f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
|
||||
return body
|
||||
what = "로켓그로스 주문" if rg else "발주서"
|
||||
for attempt in range(RETRY_429 + 1):
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
gap = RG_CALL_INTERVAL_SEC if rg else CALL_INTERVAL_SEC
|
||||
last = self._last_rg_call if rg else self._last_call
|
||||
wait = gap - (time.monotonic() - last)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||
"Content-Type": "application/json;charset=UTF-8"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise GatewayTimeout(f"쿠팡 {what} 응답 시간 초과: {type(exc).__name__}") from None
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
if rg:
|
||||
self._last_rg_call = time.monotonic()
|
||||
else:
|
||||
self._last_call = time.monotonic()
|
||||
if res.status_code == 429 and attempt < RETRY_429:
|
||||
time.sleep(2.0 * (2 ** attempt))
|
||||
continue
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
body = {"data": body}
|
||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()[:300]
|
||||
if res.status_code in (401, 403):
|
||||
raise AuthFailed(
|
||||
f"쿠팡 {what} 조회 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||
if res.status_code == 429:
|
||||
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
if res.status_code in (502, 503, 504):
|
||||
raise GatewayTimeout(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||
code = body.get("code")
|
||||
if isinstance(code, int) and code >= 400:
|
||||
raise ApiError(f"쿠팡 {what} API 오류({code}): {msg}")
|
||||
return body
|
||||
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
|
||||
def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
token: str | None = None
|
||||
for _ in range(MAX_PAGES):
|
||||
body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg)
|
||||
rows = [r for r in (body.get("data") or []) if isinstance(r, dict)] if isinstance(body.get("data"), list) else []
|
||||
out.extend(rows)
|
||||
nxt = str(body.get("nextToken") or "").strip()
|
||||
if not nxt or not rows or nxt == token:
|
||||
break
|
||||
token = nxt
|
||||
return out
|
||||
|
||||
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가.
|
||||
|
||||
건수가 많은 상태(배송완료 등)는 31일을 한 번에 부르면 쿠팡 서버가 504(시간 초과)를 낸다 — 그러면 그 구간을
|
||||
반으로 줄여 다시 부르고(하루까지), 줄인 크기는 같은 상태의 다음 구간에도 그대로 쓴다(매번 31일로 실패하지 않게)."""
|
||||
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
size_by_status = {st: ORDER_SPAN_DAYS for st in STATUSES}
|
||||
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||
for st in STATUSES:
|
||||
rows: list[dict[str, Any]] = []
|
||||
d, tries = a, 0
|
||||
while d <= b:
|
||||
e = min(b, d + timedelta(days=size_by_status[st] - 1))
|
||||
try:
|
||||
part = self._pages(ctx, path, {"createdAtFrom": f"{d.isoformat()}+09:00",
|
||||
"createdAtTo": f"{e.isoformat()}+09:00",
|
||||
"status": st, "maxPerPage": PAGE_SIZE})
|
||||
except GatewayTimeout as exc:
|
||||
if size_by_status[st] > 1:
|
||||
size_by_status[st] = max(1, size_by_status[st] // 2)
|
||||
continue
|
||||
tries += 1
|
||||
if tries <= RETRY_TIMEOUT_1DAY:
|
||||
time.sleep(3.0 * tries)
|
||||
continue
|
||||
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] "
|
||||
"— 잠시 뒤 다시 시도하세요.") from None
|
||||
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
|
||||
raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None
|
||||
rows.extend(part)
|
||||
d, tries = e + timedelta(days=1), 0
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
|
||||
def _rg_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in spans(start, end, RG_SPAN_DAYS):
|
||||
rows: list[dict[str, Any]] = []
|
||||
d, size, tries = a, RG_SPAN_DAYS, 0
|
||||
while d <= b: # 시간 초과면 판매자배송과 같이 구간을 반으로(하루까지)
|
||||
e = min(b, d + timedelta(days=size - 1))
|
||||
try:
|
||||
part = self._pages(ctx, path, {"paidDateFrom": d.strftime("%Y%m%d"),
|
||||
"paidDateTo": e.strftime("%Y%m%d")}, rg=True)
|
||||
except GatewayTimeout as exc:
|
||||
if size > 1:
|
||||
size = max(1, size // 2)
|
||||
continue
|
||||
tries += 1
|
||||
if tries <= RETRY_TIMEOUT_1DAY:
|
||||
time.sleep(3.0 * tries)
|
||||
continue
|
||||
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] "
|
||||
"— 잠시 뒤 다시 시도하세요.") from None
|
||||
except ApiError as exc:
|
||||
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None
|
||||
rows.extend(part)
|
||||
d, tries = e + timedelta(days=1), 0
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
|
||||
def _plan(self, ctx: AdapterContext, start: date, end: date) -> None:
|
||||
ctx.progress.plan(len(spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS)) * len(STATUSES)
|
||||
+ len(spans(start, end, RG_SPAN_DAYS)), "조회")
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
self._plan(ctx, start, end)
|
||||
seller = seller_lines(self._seller_orders(ctx, start, end), start, end)
|
||||
rg = rg_lines(self._rg_orders(ctx, start, end), start, end)
|
||||
yield from group_lines(seller, EVENT_PREFIX).values()
|
||||
yield from group_lines(rg, RG_PREFIX).values()
|
||||
|
||||
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||
oid, day = str(o.get("orderId") or ""), o.get("_day")
|
||||
if not oid or day is None:
|
||||
return []
|
||||
names = o.get("names") or []
|
||||
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
|
||||
if o.get("canceled"):
|
||||
statuses.append("취소 포함")
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=str(o["event_id"]), external_order_id=oid,
|
||||
order_date=o.get("order_day"), payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
|
||||
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
|
||||
discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50],
|
||||
)]
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
self.authenticate(ctx)
|
||||
vendor = ctx.credentials.get("vendor_id").strip()
|
||||
today = today_kst().isoformat()
|
||||
body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
|
||||
{"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
|
||||
vendor = self._vendor(ctx)
|
||||
today = today_kst()
|
||||
body = self._get(ctx, ORDERS_PATH.format(vendor=vendor),
|
||||
{"createdAtFrom": f"{today.isoformat()}+09:00", "createdAtTo": f"{today.isoformat()}+09:00",
|
||||
"status": "ACCEPT", "maxPerPage": 1})
|
||||
n = len(body.get("data") or [])
|
||||
return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
|
||||
"매출 수집은 다음 단계에서 구현됩니다.")
|
||||
rg = self._get(ctx, RG_ORDERS_PATH.format(vendor=vendor),
|
||||
{"paidDateFrom": today.strftime("%Y%m%d"), "paidDateTo": today.strftime("%Y%m%d")}, rg=True)
|
||||
m = len(rg.get("data") or [])
|
||||
return (f"쿠팡 연결 정상(판매자배송 발주서·로켓그로스 주문 조회 권한 확인 — 오늘 결제완료 발주서 {'있음' if n else '없음'}, "
|
||||
f"로켓그로스 오늘 주문 {m}건{'+' if rg.get('nextToken') else ''}).")
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""결제일 기준 기간(최대 31일)의 판매자배송 발주서·로켓그로스 주문을 실제로 불러, 날짜별 후보 금액을 나란히 —
|
||||
WING 판매분석 '매출(원)'과 같은 열을 찾아 규칙을 확정하는 용도. 저장하지 않고, 개인정보 항목은 빼고 보여 준다."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
self._plan(ctx, day, to)
|
||||
probes: list[dict[str, Any]] = []
|
||||
seller_raw: list[dict[str, Any]] = []
|
||||
rg_raw: list[dict[str, Any]] = []
|
||||
try:
|
||||
seller_raw = self._seller_orders(ctx, day, to)
|
||||
probes.append({"key": "seller", "label": "판매자배송 발주서(주문일 하루 앞부터, 상태 6개)",
|
||||
"path": ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(seller_raw),
|
||||
"fields": field_summary([r for o in seller_raw for r in line_records(o)])})
|
||||
except AdapterError as exc:
|
||||
probes.append({"key": "seller", "label": "판매자배송 발주서", "path": ORDERS_PATH.format(vendor="{vendorId}"),
|
||||
"ok": False, "error": exc.message[:300]})
|
||||
try:
|
||||
rg_raw = self._rg_orders(ctx, day, to)
|
||||
probes.append({"key": "rg", "label": "로켓그로스 주문(결제일, 출고된 주문만)",
|
||||
"path": RG_ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(rg_raw),
|
||||
"fields": field_summary([{**flatten({k: v for k, v in o.items() if k != "orderItems"}),
|
||||
**flatten(it, "orderItems")}
|
||||
for o in rg_raw for it in (o.get("orderItems") or [{}])])})
|
||||
except AdapterError as exc:
|
||||
probes.append({"key": "rg", "label": "로켓그로스 주문", "path": RG_ORDERS_PATH.format(vendor="{vendorId}"),
|
||||
"ok": False, "error": exc.message[:300]})
|
||||
seller = seller_lines(seller_raw, day, to)
|
||||
rg = rg_lines(rg_raw, day, to)
|
||||
dates = [(day + timedelta(days=i)).isoformat() for i in range((to - day).days + 1)]
|
||||
|
||||
def per_day(lines: list[dict[str, Any]], fn: Any) -> dict[str, int]:
|
||||
out = {d: 0 for d in dates}
|
||||
for ln in lines:
|
||||
out[ln["_day"].isoformat()] += int(fn(ln))
|
||||
return out
|
||||
|
||||
def count(lines: list[dict[str, Any]], d: str) -> int:
|
||||
return len({ln["orderId"] for ln in lines if ln["_day"].isoformat() == d})
|
||||
|
||||
s_amt, s_net = per_day(seller, lambda x: x["amount"]), per_day(seller, lambda x: x["amount"] - x["discount"])
|
||||
s_live = per_day(seller, lambda x: x["amount"] - x["canceled"])
|
||||
s_qty, r_qty = per_day(seller, lambda x: x["qty"]), per_day(rg, lambda x: x["qty"])
|
||||
s_cancel, s_ship = per_day(seller, lambda x: x["canceled"]), per_day(seller, lambda x: x["ship"])
|
||||
r_amt = per_day(rg, lambda x: x["amount"])
|
||||
ok = {p["key"]: p["ok"] for p in probes}
|
||||
failed = {p["key"]: p.get("error", "") for p in probes if not p["ok"]}
|
||||
cands = [
|
||||
{"label": "① 현재 규칙: 판매자배송 판매가 + 로켓그로스", "days": {d: s_amt[d] + r_amt[d] for d in dates}},
|
||||
{"label": "② 판매자배송 판매가(쿠폰 할인 전)", "days": s_amt, "error": failed.get("seller")},
|
||||
{"label": "③ 판매자배송 할인 뒤(판매가 − 쿠폰·쿠팡 할인)", "days": s_net, "error": failed.get("seller")},
|
||||
{"label": "④ 판매자배송 취소분 뺀 판매가", "days": s_live, "error": failed.get("seller")},
|
||||
{"label": "⑤ 로켓그로스 단가 × 수량", "days": r_amt, "error": failed.get("rg")},
|
||||
{"label": "판매량: 판매자배송 + 로켓그로스(개)", "days": {d: s_qty[d] + r_qty[d] for d in dates}},
|
||||
]
|
||||
if not all(ok.values()):
|
||||
cands[0]["error"] = "일부 조회 실패 — 위 표 참고"
|
||||
days = [{"date": d, "orders": count(seller, d) + count(rg, d), "amount": s_amt[d] + r_amt[d],
|
||||
"claimed": s_cancel[d], "ship": s_ship[d]}
|
||||
for d in dates]
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"day_cols": {"amount": "매출(현재 규칙)", "claimed": "그중 판매자배송 취소분(참고)", "ship": "판매자배송 배송비(참고, 매출 제외)"},
|
||||
"refund_candidates": cands, "candidates_title": "매출 후보 비교 — WING 판매분석 '매출(원)'·'판매량'과 같은 열을 알려 주세요",
|
||||
"rule": "결제일(한국 시간) 기준 — 판매자배송 발주서 orderPrice(판매가 × 수량, 쿠폰 할인 전, 결제 뒤 취소분 포함) + "
|
||||
"로켓그로스 unitSalesPrice × salesQuantity(출고된 주문만). 배송비 제외"}
|
||||
|
||||
@@ -1,21 +1,366 @@
|
||||
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
|
||||
"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인).
|
||||
|
||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
||||
인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com
|
||||
Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키
|
||||
Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키
|
||||
channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다)
|
||||
두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."},
|
||||
판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"},
|
||||
연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다."
|
||||
Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”).
|
||||
|
||||
매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함):
|
||||
- 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=)
|
||||
— 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음).
|
||||
목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …).
|
||||
- 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다.
|
||||
한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시).
|
||||
- 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`),
|
||||
날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합.
|
||||
- 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice
|
||||
− adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**.
|
||||
설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다.
|
||||
- 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다.
|
||||
- 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
import re
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
)
|
||||
from .naver import field_summary, flatten
|
||||
|
||||
HOST = "https://kapi.kakao.com"
|
||||
PAID_PATH = "/v2/shopping/orders/paidAt"
|
||||
ORDER_PATH = "/v1/shopping/order"
|
||||
EVENT_PREFIX = "kakao:"
|
||||
DEFAULT_CHANNELS = "101" # 톡스토어
|
||||
PAGE_SIZE = 100
|
||||
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
|
||||
CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히)
|
||||
RETRY_429 = 3
|
||||
PROBE_MAX_DAYS = 31
|
||||
CACHE_MAX = 20000
|
||||
|
||||
# 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준).
|
||||
UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"})
|
||||
# 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
|
||||
CLAIMED_STATUS = frozenset({
|
||||
"PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete",
|
||||
"ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete",
|
||||
})
|
||||
STATUS_KO = {
|
||||
"Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중",
|
||||
"PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청",
|
||||
"PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료",
|
||||
"UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중",
|
||||
"ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료",
|
||||
"ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청",
|
||||
"ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료",
|
||||
"TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료",
|
||||
"BuyDecision": "구매 결정",
|
||||
}
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
try:
|
||||
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _day(value: Any) -> date | None:
|
||||
""""20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간."""
|
||||
s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8]
|
||||
if len(s) < 8:
|
||||
return None
|
||||
try:
|
||||
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def line_amount(op: dict[str, Any]) -> int:
|
||||
"""상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외."""
|
||||
qty = max(1, _won(op.get("quantity")))
|
||||
gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty
|
||||
return max(0, gross - line_discount(op))
|
||||
|
||||
|
||||
def line_discount(op: dict[str, Any]) -> int:
|
||||
return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice"))
|
||||
|
||||
|
||||
# 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김).
|
||||
PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver")
|
||||
PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment")
|
||||
|
||||
|
||||
def strip_personal(det: dict[str, Any]) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {}
|
||||
for k, v in det.items():
|
||||
if k in PERSONAL_OBJECTS and isinstance(v, dict):
|
||||
out[k] = {kk: "" for kk in v}
|
||||
elif isinstance(v, dict):
|
||||
out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()}
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
def order_detail(body: Any) -> dict[str, Any]:
|
||||
"""주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움).
|
||||
감싼 모양(data/content)도 받아들인다."""
|
||||
if not isinstance(body, dict):
|
||||
return {}
|
||||
if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict):
|
||||
return strip_personal(body)
|
||||
for k in ("data", "content", "contents"):
|
||||
v = body.get(k)
|
||||
if isinstance(v, list) and v and isinstance(v[0], dict):
|
||||
v = v[0]
|
||||
if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)):
|
||||
return strip_personal(v)
|
||||
return {}
|
||||
|
||||
|
||||
def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||
"""주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||
items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
|
||||
pays: dict[str, dict[str, Any]] = {}
|
||||
for it in items:
|
||||
row, det = it.get("row") or {}, it.get("detail") or {}
|
||||
base, op = det.get("orderBase") or {}, det.get("orderProduct") or {}
|
||||
status = str(row.get("orderStatus") or base.get("status") or "")
|
||||
day = _day(row.get("paidAt") or base.get("paidAt"))
|
||||
oid = str(row.get("orderId") or base.get("id") or det.get("id") or "")
|
||||
pid = str(row.get("paymentId") or base.get("paymentId") or oid)
|
||||
if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op:
|
||||
continue
|
||||
p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||
"discount": 0, "names": [], "opt": "", "statuses": [], "orders": [],
|
||||
"order_day": _day(row.get("createdAt") or base.get("createdAt"))})
|
||||
amt = line_amount(op)
|
||||
p["amount"] += amt
|
||||
if status in CLAIMED_STATUS:
|
||||
p["claimed"] += amt
|
||||
p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount"))
|
||||
p["qty"] += max(1, _won(op.get("quantity")))
|
||||
p["discount"] += line_discount(op)
|
||||
p["orders"].append(oid)
|
||||
name = str(op.get("name") or "")
|
||||
if name and name not in p["names"]:
|
||||
p["names"].append(name)
|
||||
p["opt"] = p["opt"] or str(op.get("optionContent") or "")
|
||||
if status and status not in p["statuses"]:
|
||||
p["statuses"].append(status)
|
||||
return pays
|
||||
|
||||
|
||||
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||
parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")]
|
||||
ex = body.get("extras")
|
||||
if isinstance(ex, dict):
|
||||
parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")]
|
||||
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||
|
||||
|
||||
class KakaoAdapter(MarketplaceAdapter):
|
||||
code = "kakao"
|
||||
name = "카카오"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975"
|
||||
note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. "
|
||||
"그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. "
|
||||
"두 키는 서로 다른 앱의 키여야 합니다.")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_call = 0.0
|
||||
self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보)
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
# api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게.
|
||||
return [
|
||||
CredentialField("seller_id", "판매자(채널) ID"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True,
|
||||
help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"),
|
||||
CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True,
|
||||
help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"),
|
||||
CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS,
|
||||
help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"),
|
||||
]
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
def _headers(self, ctx: AdapterContext) -> dict[str, str]:
|
||||
admin = ctx.credentials.get("admin_key").strip()
|
||||
seller = ctx.credentials.get("api_key").strip()
|
||||
if not admin or not seller:
|
||||
raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.")
|
||||
channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS
|
||||
return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}",
|
||||
"channel-ids": channels, "Accept": "application/json"}
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내)."""
|
||||
import httpx # 지연 import
|
||||
|
||||
headers = self._headers(ctx)
|
||||
for attempt in range(RETRY_429 + 1):
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"카카오쇼핑 API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
self._last_call = time.monotonic()
|
||||
if res.status_code == 429 and attempt < RETRY_429:
|
||||
time.sleep(1.0 * (2 ** attempt))
|
||||
continue
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
body = {"contents": body}
|
||||
code = _won(body.get("code")) if body.get("code") not in (None, "") else 0
|
||||
text = _err_text(body, res)
|
||||
if code == -2 or "target-authorization" in text.lower():
|
||||
raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, "
|
||||
"어드민 키가 REST API 키가 아닌지 확인하세요.")
|
||||
if code == -401 or "deactivated" in text:
|
||||
raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.")
|
||||
if "매핑" in text or "대행사" in text:
|
||||
raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 "
|
||||
"끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.")
|
||||
if res.status_code in (401, 403):
|
||||
raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, "
|
||||
"두 키가 맞는지 확인하세요.")
|
||||
if res.status_code >= 400 or code < 0:
|
||||
raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}")
|
||||
return body
|
||||
raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
|
||||
def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
|
||||
"""결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음."""
|
||||
params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59",
|
||||
"size": PAGE_SIZE}
|
||||
out: list[dict[str, Any]] = []
|
||||
token = ""
|
||||
for _ in range(MAX_PAGES):
|
||||
body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})})
|
||||
rows = [r for r in body.get("contents") or [] if isinstance(r, dict)]
|
||||
out.extend(rows)
|
||||
token = str(body.get("token") or "")
|
||||
if not token or not rows:
|
||||
break
|
||||
return out
|
||||
|
||||
def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]:
|
||||
oid = str(row.get("orderId") or "")
|
||||
mod = str(row.get("modifiedAt") or "")
|
||||
hit = self._details.get(oid)
|
||||
if hit and hit[0] == mod and mod:
|
||||
return hit[1]
|
||||
det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid}))
|
||||
if det:
|
||||
if len(self._details) >= CACHE_MAX:
|
||||
self._details.clear()
|
||||
self._details[oid] = (mod, det)
|
||||
return det
|
||||
|
||||
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
"""하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}."""
|
||||
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
|
||||
d = start
|
||||
while d <= end:
|
||||
rows = self._day_rows(ctx, d)
|
||||
got = []
|
||||
for r in rows:
|
||||
if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS:
|
||||
got.append({"row": r, "detail": {}})
|
||||
continue
|
||||
got.append({"row": r, "detail": self._detail(ctx, r)})
|
||||
ctx.progress.step(items=len(rows))
|
||||
yield from got
|
||||
d += timedelta(days=1)
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
yield from group_payments(self._items(ctx, start, end), start, end).values()
|
||||
|
||||
def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]:
|
||||
pid, day = str(p.get("paymentId") or ""), p.get("_day")
|
||||
if not pid or day is None:
|
||||
return []
|
||||
names = p.get("names") or []
|
||||
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||
statuses = [STATUS_KO.get(s, s) for s in p.get("statuses") or []]
|
||||
orders = p.get("orders") or []
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid,
|
||||
external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day,
|
||||
amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200],
|
||||
quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)),
|
||||
order_status="/".join(statuses)[:50],
|
||||
)]
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
self.authenticate(ctx)
|
||||
rows = self._day_rows(ctx, today_kst())
|
||||
return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)."
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""결제일 기준 기간(최대 31일)의 주문과 주문정보를 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을
|
||||
돌려준다(저장 안 함). 판매자센터 매출 화면과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보는 이름만."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
try:
|
||||
items = list(self._items(ctx, day, to))
|
||||
except AdapterError as exc:
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||
{"key": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||
flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items]
|
||||
probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}",
|
||||
"ok": True, "count": len(items), "fields": field_summary(flat)}]
|
||||
by_status: dict[str, list[dict[str, str]]] = {}
|
||||
for it, f in zip(items, flat):
|
||||
by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f)
|
||||
for st, rows in sorted(by_status.items()):
|
||||
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
|
||||
+ (" — 매출 제외(미결제)" if st in UNPAID_STATUS else
|
||||
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus",
|
||||
"ok": True, "count": len(rows),
|
||||
"fields": [f for f in field_summary(rows)
|
||||
if f["sum"] is not None and f["name"].startswith("orderProduct.")]})
|
||||
pays = group_payments(items, day, to)
|
||||
days = []
|
||||
d = day
|
||||
while d <= to:
|
||||
day_pays = [p for p in pays.values() if p["_day"] == d]
|
||||
days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays),
|
||||
"claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)})
|
||||
d += timedelta(days=1)
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, "
|
||||
"결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""수동 입력 전용 쇼핑몰 — API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 넣는다.
|
||||
|
||||
어댑터는 쇼핑몰의 "종류"만 알린다: 인증 항목이 없고(manual_only), 매출 업데이트(sync_all)에서 빠진다.
|
||||
DB(perf_marketplaces)에는 manual_input = TRUE 로 넣는다(마이그레이션 003).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import MarketplaceAdapter
|
||||
|
||||
|
||||
class ManualOnlyAdapter(MarketplaceAdapter):
|
||||
auth_type = "manual"
|
||||
manual_only = True
|
||||
note = "API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 입력합니다."
|
||||
|
||||
|
||||
class CoupangRocketAdapter(ManualOnlyAdapter):
|
||||
code = "coupang_rocket"
|
||||
name = "쿠팡(로켓)"
|
||||
|
||||
|
||||
class AtomyAzmallAdapter(ManualOnlyAdapter):
|
||||
code = "atomy"
|
||||
name = "애터미아자몰"
|
||||
@@ -202,7 +202,7 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
|
||||
|
||||
class NaverAdapter(MarketplaceAdapter):
|
||||
code = "naver"
|
||||
name = "네이버 스마트스토어"
|
||||
name = "네이버"
|
||||
auth_type = "oauth"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
|
||||
@@ -14,14 +14,17 @@ from .gmarket import GmarketAdapter
|
||||
from .gsshop import GsshopAdapter
|
||||
from .kakao import KakaoAdapter
|
||||
from .lotteon import LotteonAdapter
|
||||
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
|
||||
from .naver import NaverAdapter
|
||||
from .ohouse import OhouseAdapter
|
||||
from .toss import TossAdapter
|
||||
|
||||
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 003)
|
||||
Cafe24Adapter(),
|
||||
NaverAdapter(),
|
||||
CoupangAdapter(),
|
||||
CoupangAdapter(), # 쿠팡(윙)
|
||||
CoupangRocketAdapter(), # 쿠팡(로켓) — 수동 입력 전용
|
||||
OhouseAdapter(),
|
||||
GmarketAdapter(),
|
||||
KakaoAdapter(),
|
||||
@@ -29,6 +32,7 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||
ElevenstAdapter(),
|
||||
LotteonAdapter(),
|
||||
TossAdapter(),
|
||||
AtomyAzmallAdapter(), # 애터미아자몰 — 수동 입력 전용
|
||||
)
|
||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||
|
||||
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||
|
||||
환경변수(.env)
|
||||
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
|
||||
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
||||
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.timezone import now_kst
|
||||
|
||||
logger = logging.getLogger("performance.auto_sync")
|
||||
|
||||
AUTO_USER = "자동 업데이트"
|
||||
DEFAULT_DAYS = 10
|
||||
DEFAULT_HOURS = (9, 19)
|
||||
SLOT_MINUTES = 30
|
||||
|
||||
_started = False
|
||||
_start_lock = threading.Lock()
|
||||
|
||||
|
||||
def _env(name: str) -> str:
|
||||
return (os.getenv(name, "") or "").strip()
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
|
||||
|
||||
|
||||
def sync_days() -> int:
|
||||
try:
|
||||
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
|
||||
except ValueError:
|
||||
return DEFAULT_DAYS
|
||||
|
||||
|
||||
def hour_window() -> tuple[int, int]:
|
||||
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
|
||||
if not m:
|
||||
return DEFAULT_HOURS
|
||||
first, last = int(m.group(1)), int(m.group(2))
|
||||
if not (0 <= first <= last <= 23):
|
||||
return DEFAULT_HOURS
|
||||
return first, last
|
||||
|
||||
|
||||
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
|
||||
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
|
||||
first, last = hours
|
||||
if t.minute % SLOT_MINUTES:
|
||||
return False
|
||||
return first <= t.hour < last or (t.hour == last and t.minute == 0)
|
||||
|
||||
|
||||
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
|
||||
"""after 보다 뒤의 첫 회차 시각."""
|
||||
t = after.replace(second=0, microsecond=0)
|
||||
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
|
||||
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
|
||||
if is_slot(t, hours):
|
||||
return t
|
||||
t += timedelta(minutes=SLOT_MINUTES)
|
||||
raise ValueError("회차를 찾을 수 없습니다")
|
||||
|
||||
|
||||
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
||||
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
|
||||
from . import common, jobs # noqa: WPS433
|
||||
from .credentials import CredentialService # noqa: WPS433
|
||||
from .sync import SyncService # noqa: WPS433
|
||||
|
||||
if jobs.running_job() is not None:
|
||||
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
|
||||
start, end = today - timedelta(days=days - 1), today
|
||||
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
|
||||
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
|
||||
error = ""
|
||||
results: list[dict[str, Any]] = []
|
||||
try:
|
||||
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
|
||||
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
|
||||
logger.exception("auto sync failed")
|
||||
error = f"업데이트 중 오류: {type(exc).__name__}"
|
||||
last = None
|
||||
try:
|
||||
last = store.last_update_at()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
job.finish(error=error, last_update_at=last)
|
||||
ok = sum(1 for r in results if r.get("ok"))
|
||||
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error}
|
||||
|
||||
|
||||
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
||||
global _started # noqa: PLW0603
|
||||
store = getattr(app_state, "performance_store", None)
|
||||
if store is None or not enabled():
|
||||
return False
|
||||
with _start_lock:
|
||||
if _started:
|
||||
return False
|
||||
_started = True
|
||||
hours, days = hour_window(), sync_days()
|
||||
|
||||
def _loop() -> None:
|
||||
due = next_slot(now_kst(), hours)
|
||||
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
|
||||
due.strftime("%m-%d %H:%M"))
|
||||
while True:
|
||||
wait = (due - now_kst()).total_seconds()
|
||||
if wait > 0:
|
||||
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
|
||||
continue
|
||||
try:
|
||||
res = run_once(store, app_state, today=due.date(), days=days)
|
||||
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
|
||||
due = next_slot(max(now_kst(), due), hours)
|
||||
|
||||
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
|
||||
return True
|
||||
@@ -25,6 +25,8 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
|
||||
if not marketplace.get("enabled"):
|
||||
return "disabled"
|
||||
adapter = get_adapter(marketplace["code"])
|
||||
if adapter is not None and adapter.manual_only:
|
||||
return "manual"
|
||||
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
||||
return "not_configured"
|
||||
return (status_row or {}).get("status") or "unknown"
|
||||
@@ -58,6 +60,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||
q_end = max(period.end, year_period.end)
|
||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
||||
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
||||
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
|
||||
manual_amounts = getattr(store, "manual_amounts", None)
|
||||
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
|
||||
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
|
||||
|
||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||
@@ -143,6 +150,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"chart_daily": calc.daily_series(period, codes, cells),
|
||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
||||
"problems": problems,
|
||||
"manual_codes": manual_codes,
|
||||
"manual_cells": manual_cells,
|
||||
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
|
||||
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
|
||||
"last_update_at": store.last_update_at(),
|
||||
"running": store.running_codes(),
|
||||
"no_marketplaces": not all_codes,
|
||||
@@ -175,10 +186,11 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
||||
has_rate = bool(rates.get(adapter.code))
|
||||
rows.append({
|
||||
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
||||
"include_in_sales": m["include_in_sales"],
|
||||
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
|
||||
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
||||
"rate_history": len(rates.get(adapter.code, ())),
|
||||
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
||||
"manual_only": adapter.manual_only,
|
||||
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
||||
"configured": configured.get(adapter.code, False),
|
||||
"via_cafe24": adapter.code in via_cafe24,
|
||||
|
||||
@@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Iterable
|
||||
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
@@ -25,6 +26,10 @@ from app.timezone import to_kst_iso
|
||||
STALE_RUN_AFTER = timedelta(minutes=30)
|
||||
|
||||
|
||||
class ManualMigrationNeeded(Exception):
|
||||
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
||||
|
||||
|
||||
def _iso(v: Any) -> Any:
|
||||
if isinstance(v, datetime):
|
||||
return to_kst_iso(v)
|
||||
@@ -56,8 +61,12 @@ class PerformanceDBStore:
|
||||
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
||||
|
||||
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
||||
include_in_sales: bool | None = None) -> dict[str, Any] | None:
|
||||
include_in_sales: bool | None = None,
|
||||
manual_input: bool | None = None) -> dict[str, Any] | None:
|
||||
sets, params = [], []
|
||||
if manual_input is not None:
|
||||
sets.append("manual_input = %s")
|
||||
params.append(bool(manual_input))
|
||||
if enabled is not None:
|
||||
sets.append("enabled = %s")
|
||||
params.append(bool(enabled))
|
||||
@@ -67,10 +76,13 @@ class PerformanceDBStore:
|
||||
if not sets:
|
||||
return None
|
||||
params.append(code)
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
||||
).fetchone()
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
||||
).fetchone()
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise ManualMigrationNeeded() from None
|
||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -281,6 +293,8 @@ class PerformanceDBStore:
|
||||
"""
|
||||
|
||||
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
||||
"""날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다
|
||||
(실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다)."""
|
||||
if not codes:
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
@@ -290,7 +304,170 @@ class PerformanceDBStore:
|
||||
"GROUP BY sales_date, marketplace_code",
|
||||
(start, end, codes),
|
||||
).fetchall()
|
||||
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
||||
out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
||||
out.update(self.manual_amounts(start, end, codes))
|
||||
return out
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 수동 입력 매출(마이그레이션 002)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def manual_amounts(self, start: date, end: date, codes: list[str], *,
|
||||
active_only: bool = True) -> dict[tuple[date, str], int]:
|
||||
"""수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음."""
|
||||
if not codes:
|
||||
return {}
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s "
|
||||
"JOIN perf_marketplaces m ON m.code = s.marketplace_code "
|
||||
"WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)"
|
||||
+ (" AND m.manual_input" if active_only else ""),
|
||||
(start, end, codes),
|
||||
).fetchall()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return {}
|
||||
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows}
|
||||
|
||||
def api_amount(self, code: str, day: date) -> int:
|
||||
"""그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events "
|
||||
"WHERE marketplace_code = %s AND sales_date = %s", (code, day),
|
||||
).fetchone()
|
||||
return int(row["amount"] or 0)
|
||||
|
||||
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None:
|
||||
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값)."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
if amount is None:
|
||||
conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s",
|
||||
(code, day))
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||
(code, day, int(amount), user),
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise ManualMigrationNeeded() from None
|
||||
|
||||
def set_manual_sales_bulk(self, entries: list[tuple[str, date, int]], *, user: str = "") -> int:
|
||||
"""엑셀 업로드 — (쇼핑몰, 날짜, 금액) 여러 개를 한 트랜잭션으로 저장(덮어씀). 하나라도 실패하면 모두 취소."""
|
||||
if not entries:
|
||||
return 0
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||
[(code, day, int(amount), user) for code, day, amount in entries],
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise ManualMigrationNeeded() from None
|
||||
return len(entries)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 광고비(마이그레이션 005)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]:
|
||||
"""(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT spend_date, channel_code, amount, source FROM perf_ad_spend "
|
||||
"WHERE spend_date BETWEEN %s AND %s", (start, end),
|
||||
).fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded() from None
|
||||
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
|
||||
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
|
||||
|
||||
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None:
|
||||
"""광고비 한 칸 저장(amount None = 지움)."""
|
||||
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||
|
||||
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
|
||||
user: str = "", roas: dict[date, Any] | None = None,
|
||||
metrics: dict[date, dict[str, Any]] | None = None) -> int:
|
||||
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
|
||||
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
if not entries:
|
||||
return 0
|
||||
report = roas is not None or metrics is not None
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
gone = [(code, d) for d, a in entries if a is None]
|
||||
if gone:
|
||||
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
|
||||
if report:
|
||||
keep6 = [(code, d, int(a), source, user, (roas or {}).get(d),
|
||||
Jsonb((metrics or {}).get(d)) if (metrics or {}).get(d) is not None else None)
|
||||
for d, a in entries if a is not None]
|
||||
if keep6:
|
||||
cur.executemany(
|
||||
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
|
||||
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
|
||||
keep6,
|
||||
)
|
||||
else:
|
||||
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
|
||||
if keep:
|
||||
cur.executemany(
|
||||
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
|
||||
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
|
||||
keep,
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded("005") from None
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise AdMigrationNeeded("006") from None
|
||||
return len(entries)
|
||||
|
||||
def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
|
||||
"""(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이)."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT spend_date, channel_code, roas FROM perf_ad_spend "
|
||||
"WHERE spend_date BETWEEN %s AND %s AND roas IS NOT NULL", (start, end),
|
||||
).fetchall()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return {}
|
||||
return {(r["spend_date"], r["channel_code"]): r["roas"] for r in rows}
|
||||
|
||||
def ad_details(self, code: str, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""한 채널의 일자별 광고비·ROAS·보고서 항목(날짜 순). 006 미적용이면 AdMigrationNeeded."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT spend_date, amount, roas, metrics, source FROM perf_ad_spend "
|
||||
"WHERE channel_code = %s AND spend_date BETWEEN %s AND %s ORDER BY spend_date",
|
||||
(code, start, end),
|
||||
).fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded("005") from None
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise AdMigrationNeeded("006") from None
|
||||
return [{"date": r["spend_date"].isoformat(), "amount": int(r["amount"]), "roas": r["roas"],
|
||||
"metrics": r["metrics"] or {}, "source": r["source"]} for r in rows]
|
||||
|
||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""수동 입력 매출 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글(샘플: upload_sample.xlsx).
|
||||
|
||||
규칙
|
||||
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
|
||||
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
|
||||
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
|
||||
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨.
|
||||
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
|
||||
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
|
||||
|
||||
HTTP·DB 와 무관한 순수 함수 — 라우터가 파일 바이트와 쇼핑몰 목록을 넘긴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
MAX_FILE_BYTES = 5 * 1024 * 1024
|
||||
MAX_DATA_ROWS = 2000
|
||||
MAX_ERRORS = 30
|
||||
MAX_AMOUNT = 10 ** 12 # 라우터 MAX_MANUAL_AMOUNT 와 같은 상한(원)
|
||||
|
||||
_EXCEL_EPOCH = date(1899, 12, 30)
|
||||
_DATE_RE = re.compile(r"^(\d{4})\s*[-./년]\s*(\d{1,2})\s*[-./월]\s*(\d{1,2})")
|
||||
_COMPACT_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?!\d)")
|
||||
|
||||
|
||||
class UploadError(ValueError):
|
||||
"""파일 자체를 읽을 수 없음(형식·크기·머리글)."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParseResult:
|
||||
entries: list[tuple[str, date, int]] = field(default_factory=list) # (쇼핑몰 코드, 날짜, 금액)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
ignored: list[str] = field(default_factory=list) # 건너뛴 열(머리글 + 이유)
|
||||
columns: list[str] = field(default_factory=list) # 반영 대상 쇼핑몰 코드(열 순서)
|
||||
|
||||
|
||||
def _norm(text: Any) -> str:
|
||||
return re.sub(r"\s+", "", str(text or "")).lower()
|
||||
|
||||
|
||||
def _cell_ref(row: int, col: int) -> str:
|
||||
letters = ""
|
||||
n = col
|
||||
while n:
|
||||
n, r = divmod(n - 1, 26)
|
||||
letters = chr(65 + r) + letters
|
||||
return f"{letters}{row}"
|
||||
|
||||
|
||||
def parse_date(value: Any) -> date | None:
|
||||
"""날짜 칸 → date. 읽을 수 없으면 ValueError, 빈 칸이면 None."""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
n = int(value)
|
||||
if 19000101 <= n <= 29991231: # 20261012
|
||||
return parse_date(str(n))
|
||||
if 20000 <= n <= 80000: # 엑셀 날짜 일련번호(서식 없는 날짜)
|
||||
return _EXCEL_EPOCH + timedelta(days=n)
|
||||
raise ValueError
|
||||
text = str(value).strip()
|
||||
m = _DATE_RE.match(text) or _COMPACT_RE.match(text)
|
||||
if not m:
|
||||
raise ValueError
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
|
||||
|
||||
def parse_amount(value: Any) -> int | None:
|
||||
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||
if value is None or isinstance(value, bool):
|
||||
if value is None:
|
||||
return None
|
||||
raise ValueError
|
||||
if isinstance(value, (int, float, Decimal)):
|
||||
num = Decimal(str(value))
|
||||
else:
|
||||
text = re.sub(r"[,\s원₩]", "", str(value))
|
||||
if text == "":
|
||||
return None
|
||||
try:
|
||||
num = Decimal(text)
|
||||
except InvalidOperation:
|
||||
raise ValueError from None
|
||||
if not num.is_finite():
|
||||
raise ValueError
|
||||
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
|
||||
"""머리글로 쓸 수 있는 이름 → 쇼핑몰 코드. markets: code·name, extra_names: 코드별 다른 이름(어댑터 이름·짧은 이름)."""
|
||||
out: dict[str, str] = {}
|
||||
for m in markets:
|
||||
code = str(m["code"])
|
||||
for alias in (code, m.get("name"), *((extra_names or {}).get(code) or ())):
|
||||
key = _norm(alias)
|
||||
if key:
|
||||
out.setdefault(key, code)
|
||||
return out
|
||||
|
||||
|
||||
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
|
||||
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
|
||||
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
|
||||
if not content:
|
||||
raise UploadError("빈 파일입니다.")
|
||||
if len(content) > MAX_FILE_BYTES:
|
||||
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||
try:
|
||||
import openpyxl # noqa: WPS433
|
||||
|
||||
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||
raise UploadError("엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.") from None
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
rows = ws.iter_rows(values_only=True)
|
||||
header = next(rows, None)
|
||||
if not header or len(header) < 2:
|
||||
raise UploadError("1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.")
|
||||
|
||||
aliases = header_aliases(markets, extra_names)
|
||||
by_code = {str(m["code"]): m for m in markets}
|
||||
res = ParseResult()
|
||||
col_code: dict[int, str] = {} # 열 번호(0부터) → 반영할 쇼핑몰 코드
|
||||
for idx, title in enumerate(header[1:], start=1):
|
||||
if title is None or not str(title).strip():
|
||||
continue
|
||||
label = str(title).strip()
|
||||
code = aliases.get(_norm(label))
|
||||
if code is None:
|
||||
res.ignored.append(f"{label}(알 수 없는 쇼핑몰)")
|
||||
elif not by_code[code].get("manual_input"):
|
||||
res.ignored.append(f"{label}(수동 입력 꺼짐)")
|
||||
elif code in col_code.values():
|
||||
res.errors.append(f"{_cell_ref(1, idx + 1)} {label}: 같은 쇼핑몰 열이 두 번 있습니다.")
|
||||
else:
|
||||
col_code[idx] = code
|
||||
res.columns.append(code)
|
||||
if not col_code and not res.errors:
|
||||
raise UploadError("반영할 쇼핑몰 열이 없습니다. 머리글을 수동 입력이 켜진 쇼핑몰 이름으로 적어 주세요."
|
||||
+ (f" (건너뛴 열: {', '.join(res.ignored)})" if res.ignored else ""))
|
||||
|
||||
seen: dict[tuple[str, date], str] = {}
|
||||
data_rows = 0
|
||||
for r, row in enumerate(rows, start=2):
|
||||
row = tuple(row or ())
|
||||
cells = {i: (row[i] if i < len(row) else None) for i in col_code}
|
||||
amounts: dict[int, int] = {}
|
||||
for i, raw in cells.items():
|
||||
try:
|
||||
amt = parse_amount(raw)
|
||||
except ValueError:
|
||||
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
|
||||
continue
|
||||
if amt is None:
|
||||
continue
|
||||
if abs(amt) > MAX_AMOUNT:
|
||||
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 너무 큽니다.")
|
||||
continue
|
||||
amounts[i] = amt
|
||||
raw_day = row[0] if row else None
|
||||
try:
|
||||
day = parse_date(raw_day)
|
||||
except ValueError:
|
||||
res.errors.append(f"{_cell_ref(r, 1)}: 날짜를 읽을 수 없습니다({raw_day}).")
|
||||
continue
|
||||
if day is None:
|
||||
if amounts:
|
||||
res.errors.append(f"{r}행: 날짜가 비어 있습니다.")
|
||||
continue
|
||||
if not amounts:
|
||||
continue
|
||||
data_rows += 1
|
||||
if data_rows > MAX_DATA_ROWS:
|
||||
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||
if day > today:
|
||||
res.errors.append(f"{_cell_ref(r, 1)}: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||
continue
|
||||
for i, amt in amounts.items():
|
||||
code = col_code[i]
|
||||
where = _cell_ref(r, i + 1)
|
||||
if (code, day) in seen:
|
||||
res.errors.append(f"{where}: {by_code[code]['name']} {day.isoformat()} 이 {seen[(code, day)]} 와 겹칩니다.")
|
||||
continue
|
||||
seen[(code, day)] = where
|
||||
res.entries.append((code, day, amt))
|
||||
if len(res.errors) > MAX_ERRORS:
|
||||
break
|
||||
return res
|
||||
finally:
|
||||
wb.close()
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
화면
|
||||
GET /performance/ 대시보드(모듈 권한)
|
||||
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||
GET /performance/settings 실적 설정(관리자)
|
||||
JSON API — 모듈 권한
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
@@ -10,8 +11,15 @@ JSON API — 모듈 권한
|
||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
||||
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
||||
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
||||
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
||||
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
||||
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
|
||||
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
|
||||
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭)
|
||||
JSON API — 관리자
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
||||
@@ -28,10 +36,11 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi import APIRouter, Body, File, Form, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
@@ -44,6 +53,18 @@ MAX_EVENT_DAYS = 31
|
||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
|
||||
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
|
||||
|
||||
|
||||
def _ad_migration_help(exc: Exception) -> str:
|
||||
return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP
|
||||
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
|
||||
|
||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||
@@ -111,6 +132,33 @@ def dashboard_page(
|
||||
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
||||
|
||||
|
||||
@router.get("/ads", response_class=HTMLResponse)
|
||||
def ads_page(
|
||||
request: Request,
|
||||
period: str = "month",
|
||||
d: str | None = None,
|
||||
from_: str | None = Query(None, alias="from"),
|
||||
to: str | None = None,
|
||||
):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||
from .dashboard import _sales_marketplaces # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
ctx = build_ad_dashboard(
|
||||
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||
)
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
@@ -270,6 +318,198 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
||||
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
||||
|
||||
|
||||
@router.put("/api/manual-sales/{code}/{day}")
|
||||
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
|
||||
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
|
||||
_code_or_404(store, code)
|
||||
d = _parse_date(day)
|
||||
if d > today_kst():
|
||||
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
|
||||
if not m.get("manual_input"):
|
||||
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
|
||||
raw = payload.get("amount")
|
||||
amount: int | None
|
||||
if raw in (None, ""):
|
||||
amount = None
|
||||
else:
|
||||
try:
|
||||
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||
except (InvalidOperation, ValueError):
|
||||
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||
try:
|
||||
store.set_manual_sale(code, d, amount, user=user.get("email", ""))
|
||||
except ManualMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||
api_amount = store.api_amount(code, d)
|
||||
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount,
|
||||
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
|
||||
|
||||
|
||||
@router.get("/api/manual-sales/sample.xlsx")
|
||||
def api_manual_sample(request: Request) -> Any:
|
||||
common.require_store(request)
|
||||
if not MANUAL_SAMPLE_PATH.is_file():
|
||||
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
||||
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
|
||||
|
||||
@router.post("/api/manual-sales/upload")
|
||||
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||
from . import manual_upload # noqa: WPS433
|
||||
from .dashboard import _short_name # noqa: WPS433
|
||||
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
|
||||
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
|
||||
known = {a.code: a for a in all_adapters()}
|
||||
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
|
||||
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
|
||||
try:
|
||||
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
||||
except manual_upload.UploadError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
if res.errors:
|
||||
return JSONResponse(status_code=400, content={
|
||||
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
|
||||
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
|
||||
try:
|
||||
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
|
||||
except ManualMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||
counts: dict[str, int] = {}
|
||||
for code, _, _ in res.entries:
|
||||
counts[code] = counts.get(code, 0) + 1
|
||||
days = sorted({d for _, d, _ in res.entries})
|
||||
return JSONResponse({
|
||||
"ok": True, "saved": saved,
|
||||
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
|
||||
"ignored": res.ignored,
|
||||
})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 광고비(모듈 권한자 누구나)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ad_channel(channel: str) -> str:
|
||||
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||
|
||||
if channel not in CHANNEL_NAMES:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
return channel
|
||||
|
||||
|
||||
@router.put("/api/ad-spend/{channel}/{day}")
|
||||
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
_ad_channel(channel)
|
||||
d = _parse_date(day)
|
||||
if d is None:
|
||||
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
||||
if d > today_kst():
|
||||
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||
raw = payload.get("amount")
|
||||
amount: int | None
|
||||
if raw in (None, ""):
|
||||
amount = None
|
||||
else:
|
||||
try:
|
||||
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||
except (InvalidOperation, ValueError):
|
||||
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||
try:
|
||||
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
|
||||
except AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
|
||||
"amount": amount or 0})
|
||||
|
||||
|
||||
@router.get("/api/ad-spend/{channel}/details")
|
||||
def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
|
||||
"""일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
|
||||
from . import ad_spend # noqa: WPS433
|
||||
|
||||
store, _ = common.require_store(request)
|
||||
_ad_channel(channel)
|
||||
if channel not in ad_spend.DETAIL_CHANNELS:
|
||||
raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
|
||||
start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
|
||||
if start is None or end is None or end < start or (end - start).days > 365:
|
||||
raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
|
||||
try:
|
||||
rows = store.ad_details(channel, start, end)
|
||||
except ad_spend.AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
|
||||
"to": end.isoformat(), **ad_spend.detail_table(rows)})
|
||||
|
||||
|
||||
@router.post("/api/ad-spend/upload")
|
||||
def api_ad_spend_upload(
|
||||
request: Request,
|
||||
channel: str = Query(...),
|
||||
files: list[UploadFile] | None = File(None),
|
||||
file: UploadFile | None = File(None),
|
||||
modified: list[str] = Form(default=[]),
|
||||
) -> JSONResponse:
|
||||
"""광고비 파일 업로드(여러 파일 가능, 2026-10-14) — 파일에 있는 날만 덮어쓴다. 같은 날짜가 여러 파일에 있으면
|
||||
파일 날짜(브라우저가 보낸 수정 시각 modified, 파일 순서대로 ms)가 최신인 파일 값. 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다."""
|
||||
from . import ad_spend # noqa: WPS433
|
||||
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
_ad_channel(channel)
|
||||
parser = ad_spend.PARSERS.get(channel)
|
||||
if parser is None:
|
||||
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||
uploads = list(files or []) + ([file] if file is not None else [])
|
||||
if not uploads:
|
||||
raise HTTPException(status_code=400, detail="파일을 고르세요.")
|
||||
if len(uploads) > ad_spend.MAX_UPLOAD_FILES:
|
||||
raise HTTPException(status_code=400, detail=f"한 번에 {ad_spend.MAX_UPLOAD_FILES}개 파일까지 올릴 수 있습니다.")
|
||||
parsed = []
|
||||
for i, up in enumerate(uploads):
|
||||
name = up.filename or f"파일{i + 1}"
|
||||
try:
|
||||
mtime = float(modified[i]) if i < len(modified) and str(modified[i]).strip() else 0.0
|
||||
except ValueError:
|
||||
mtime = 0.0
|
||||
try:
|
||||
parsed.append((name, mtime, parser(up.file.read(MAX_FILE_BYTES + 1), today=today_kst(), filename=name)))
|
||||
except UploadError as exc:
|
||||
raise HTTPException(status_code=400, detail=(f"[{name}] " if len(uploads) > 1 else "") + str(exc)) from None
|
||||
res, overlap = ad_spend.merge_results(parsed)
|
||||
if res.errors:
|
||||
return JSONResponse(status_code=400, content={
|
||||
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||
"errors": res.errors[:60]})
|
||||
report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
|
||||
try:
|
||||
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
|
||||
except ad_spend.AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
days = sorted(d for d, _ in res.entries)
|
||||
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
||||
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
|
||||
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -277,11 +517,21 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
row = store.update_marketplace(
|
||||
code,
|
||||
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
||||
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
||||
)
|
||||
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||
|
||||
adapter = get_adapter(code)
|
||||
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
|
||||
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
|
||||
|
||||
try:
|
||||
row = store.update_marketplace(
|
||||
code,
|
||||
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
||||
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
||||
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
|
||||
)
|
||||
except ManualMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||
return JSONResponse({"marketplace": row})
|
||||
|
||||
|
||||
|
||||
@@ -162,7 +162,9 @@ class SyncService:
|
||||
end = end or today_kst()
|
||||
start = start or (end - timedelta(days=sync_days() - 1))
|
||||
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
|
||||
targets = [a for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
|
||||
# 수동 입력 전용 쇼핑몰(manual_only)은 가져올 API 가 없어 매출 업데이트에서 뺀다
|
||||
targets = [a for a in all_adapters()
|
||||
if a.code in enabled and not a.manual_only and (not codes or a.code in codes)]
|
||||
progress: dict[str, Any] = {}
|
||||
if job is not None:
|
||||
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
|
||||
<div class="perf-tabs-main" role="tablist">
|
||||
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
|
||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||
</div>
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<div class="perf-toolbar">
|
||||
<div class="perf-quick" role="group" aria-label="기간 선택">
|
||||
{% for q in nav.quick %}
|
||||
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
|
||||
{% endfor %}
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||
</div>
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if migration_needed %}
|
||||
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
|
||||
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- ── KPI ── -->
|
||||
<div class="perf-kpis">
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||
{% if k.key == 'ratio' %}
|
||||
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
||||
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
||||
{% else %}
|
||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
||||
<div class="perf-kpi-delta">
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- ── 일자 × 채널 ── -->
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
|
||||
{% if upload_channels %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
|
||||
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="erp-table-wrap perf-table-wrap">
|
||||
<table class="perf-table perf-main">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = 보고서 ROAS(구매완료 광고수익률)"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in table %}
|
||||
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
{% for c in codes %}
|
||||
{% set v = r.cells[c].gross %}
|
||||
{% if r.kind == 'day' and not r.future and not migration_needed %}
|
||||
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
|
||||
<td class="perf-num is-manual-cell{% if v and not up %} is-manual{% endif %}{% if up %} is-upload{% endif %}"
|
||||
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
|
||||
title="{% if up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% else %}
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고,
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- ── 그래프 ── -->
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
|
||||
<div class="perf-chart" id="perf-chart-daily"></div>
|
||||
</div>
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">채널별 비중</h2>
|
||||
<span class="perf-muted">{{ period.label }}</span></div>
|
||||
<div class="perf-chart" id="perf-chart-share"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── 월 누적 · 연간 누적 ── -->
|
||||
<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="erp-table-wrap">
|
||||
<table class="perf-table">
|
||||
<thead><tr><th class="perf-th-label">채널</th><th>광고비</th><th>ROAS</th><th>비중</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in month.rows %}
|
||||
<tr>
|
||||
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
<td class="perf-num perf-share">
|
||||
{% if r.share is not none %}<span class="perf-bar" style="--w: {{ [r.share, 0] | max }}%"></span>{{ "%.1f" | format(r.share) }}%{% else %}<span class="perf-zero">–</span>{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(month.total.gross) }}</td>
|
||||
<td class="perf-num">{% if month.total.roas is not none %}{{ "{:,}".format(month.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
<td class="perf-num">{% if month.total.share is not none %}100%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
|
||||
<div class="perf-year-sum">
|
||||
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-year">
|
||||
<thead><tr><th class="perf-th-label">월</th><th>광고비</th><th>ROAS</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in year.rows %}
|
||||
<tr class="{% if r.future %}is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% elif not r.future %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(year.total.gross) }}</td>
|
||||
<td class="perf-num">{% if year.total.roas is not none %}{{ "{:,}".format(year.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값).
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
구글·메타는 지금은 직접 입력합니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
"names": names,
|
||||
"codes": codes,
|
||||
"daily": chart_daily,
|
||||
"share": chart_share,
|
||||
"period_kind": period_kind,
|
||||
"today": today,
|
||||
"manual_api": "/performance/api/ad-spend/",
|
||||
"manual_word": "광고비",
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
"period_label": period.label,
|
||||
"empty_text": "기간 내 광고비가 없습니다.",
|
||||
"upload_channels": upload_channels
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -107,6 +107,10 @@
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
||||
{% 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>
|
||||
{% endif %}
|
||||
<div class="perf-metric" role="group" aria-label="표시 기준">
|
||||
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
|
||||
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
||||
@@ -118,7 +122,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}<th title="{{ names[c] }}">{{ short_names[c] }}</th>{% endfor %}
|
||||
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -130,8 +134,15 @@
|
||||
</th>
|
||||
{% for c in codes %}
|
||||
{% set m = r.cells[c] %}
|
||||
{% if r.kind == 'day' and c in manual_codes and not r.future %}
|
||||
{% 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>
|
||||
{% 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>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
|
||||
</tr>
|
||||
@@ -139,6 +150,10 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if manual_codes and period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
|
||||
비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- ── 그래프 ── -->
|
||||
@@ -235,8 +250,9 @@
|
||||
"period_kind": period_kind,
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
"today": today
|
||||
"today": today,
|
||||
"manual_upload_names": manual_upload_names
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||
{% if is_admin %}
|
||||
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
||||
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다.</span>
|
||||
{% else %}
|
||||
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||
{% endif %}
|
||||
@@ -31,7 +32,8 @@
|
||||
<tr>
|
||||
<th class="perf-th-label">쇼핑몰</th>
|
||||
{% if is_admin %}<th>사용</th>
|
||||
<th>매출 집계</th>{% endif %}
|
||||
<th>매출 집계</th>
|
||||
<th>수동 입력</th>{% endif %}
|
||||
<th>수수료율</th>
|
||||
{% if is_admin %}<th>API 설정</th>
|
||||
<th>연결 상태</th>{% endif %}
|
||||
@@ -54,6 +56,11 @@
|
||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||
</label>
|
||||
</td>
|
||||
<td class="perf-center">
|
||||
<label class="perf-switch" title="{% if r.manual_only %}수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다{% else %}수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신){% endif %}">
|
||||
<input type="checkbox" data-field="manual_input"{% if r.manual_input or r.manual_only %} checked{% endif %}{% if r.manual_only %} disabled{% endif %} /><span></span>
|
||||
</label>
|
||||
</td>
|
||||
{% endif %}
|
||||
<td class="perf-rate-cell">
|
||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
||||
@@ -62,7 +69,8 @@
|
||||
</td>
|
||||
{% if is_admin %}
|
||||
<td>
|
||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
||||
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
|
||||
{% elif r.shared %}<span class="perf-pill">공통 연동</span>
|
||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
||||
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
||||
@@ -77,8 +85,10 @@
|
||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||
{% if is_admin %}
|
||||
<td class="perf-nowrap">
|
||||
{% if not r.manual_only %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
@@ -136,13 +146,15 @@
|
||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
||||
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.</p>
|
||||
· <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="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>
|
||||
@@ -192,4 +204,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.modules.performance import ad_spend as ads
|
||||
from app.modules.performance.manual_upload import UploadError
|
||||
|
||||
TODAY = date(2026, 10, 13)
|
||||
|
||||
# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄
|
||||
ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세)
|
||||
전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494
|
||||
2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000
|
||||
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,,
|
||||
2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697
|
||||
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,,
|
||||
2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231
|
||||
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,,
|
||||
"""
|
||||
|
||||
|
||||
def _xlsx(text: str) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
for line in text.strip().splitlines():
|
||||
ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")])
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content,name", [
|
||||
(ROCKET_CSV.encode("utf-8-sig"), "report.csv"),
|
||||
(ROCKET_CSV.encode("cp949"), "report.csv"),
|
||||
(_xlsx(ROCKET_CSV), "report.xlsx"),
|
||||
])
|
||||
def test_rocket_report_reads_date_and_col19(content, name):
|
||||
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
|
||||
assert not res.errors
|
||||
assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)]
|
||||
assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개
|
||||
|
||||
|
||||
def test_rocket_report_errors_block_everything():
|
||||
bad = ROCKET_CSV + "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
|
||||
bad += "2026년 10월 08일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n" # 금액이 숫자 아님
|
||||
bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜
|
||||
res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY)
|
||||
joined = " / ".join(res.errors)
|
||||
assert len(res.errors) == 3, res.errors
|
||||
assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" in joined
|
||||
|
||||
|
||||
def test_coupang_report_date_rows_col19_summed_empty_skipped():
|
||||
"""쿠팡(윙) 보고서처럼 캠페인 줄에도 1열 날짜가 있고 19열이 비어 있어도 — 날짜가 있는 줄의 19열 값만, 같은 날은 더한다
|
||||
(2026-10-14 사용자 확인: "쿠팡은 모두 1열에서 날짜가 있는 행의 19열 값"). 값이 한 줄도 없는 날은 empty_days."""
|
||||
head = ROCKET_CSV.splitlines()[0]
|
||||
wing = "\n".join([
|
||||
head,
|
||||
"2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 날짜 있고 19열 빈 줄
|
||||
"2026-03-01,,,,VENDOR,PA,매출 성장,2,캠페인B,Adcost,DAILY_SOFT,1000,20,0,20,0,20,,",
|
||||
"2026-03-01,RETAIL,Taxable,,,,,,,,,,30,0,30,30,30,3,33", # 값 있는 줄
|
||||
"2026-03-01,RETAIL,Tax-free,,,,,,,,,,5,0,5,5,5,0,5", # 같은 날 값 한 줄 더 → 더함
|
||||
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 값 없는 날
|
||||
"2026-03-03,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,1,100", # 19열 = 1 (20열은 무시)
|
||||
]) + "\n"
|
||||
for content, name in ((wing.encode("utf-8"), "w.csv"), (_xlsx(wing), "w.xlsx")):
|
||||
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
|
||||
assert not res.errors, res.errors
|
||||
assert res.entries == [(date(2026, 3, 1), 38), (date(2026, 3, 3), 1)]
|
||||
assert res.empty_days == [date(2026, 3, 2)]
|
||||
# 청구금액이 한 줄도 없는 파일(날짜 줄만) — 오류 없이 넘어감(반영할 날 없음)
|
||||
none = "\n".join([head, "2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,",
|
||||
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,"]) + "\n"
|
||||
r0 = ads.parse_coupang_rocket(_xlsx(none), today=TODAY, filename="march.xlsx")
|
||||
assert r0.entries == [] and not r0.errors and r0.empty_days == [date(2026, 3, 1), date(2026, 3, 2)]
|
||||
m, _ = ads.merge_results([("a.xlsx", 1.0, ads.parse_coupang_rocket(wing.encode("utf-8"), today=TODAY)),
|
||||
("b.csv", 2.0, ads.ParseResult(entries=[(date(2026, 3, 2), 7)]))])
|
||||
assert m.empty_days == [] and dict(m.entries)[date(2026, 3, 2)] == 7 # 다른 파일에 값이 있으면 빈 날 아님
|
||||
|
||||
|
||||
def test_rocket_report_wrong_file():
|
||||
with pytest.raises(UploadError):
|
||||
ads.parse_coupang_rocket(b"", today=TODAY)
|
||||
with pytest.raises(UploadError): # 날짜 줄이 하나도 없음
|
||||
ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY)
|
||||
other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류
|
||||
assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0]
|
||||
with pytest.raises(UploadError):
|
||||
ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx")
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self, missing=False):
|
||||
self.missing = missing
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
if self.missing:
|
||||
raise ads.AdMigrationNeeded()
|
||||
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"),
|
||||
(date(2026, 10, 2), "google"): (50000, "manual"),
|
||||
(date(2026, 9, 1), "meta"): (100000, "manual")}
|
||||
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
rows = {(date(2026, 10, 5), "cafe24"): 2_700_000, (date(2026, 10, 1), "coupang_rocket"): 550_000,
|
||||
(date(2026, 10, 3), "coupang_rocket"): 110_000}
|
||||
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
|
||||
def test_ad_dashboard_month():
|
||||
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24"])
|
||||
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||
k = {x["key"]: x for x in ctx["kpis"]}
|
||||
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
|
||||
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
|
||||
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
||||
assert ctx["detail_channels"] == ["naver"]
|
||||
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
|
||||
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
|
||||
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
|
||||
# ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0%
|
||||
assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None
|
||||
day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02")
|
||||
assert day2["roas"]["google"] is None # 구글·메타는 ROAS 계산 안 함(따로 입력)
|
||||
total = ctx["table"][-1]
|
||||
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] is None # 660,000÷220,000
|
||||
assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes)
|
||||
m = {r["code"]: r for r in ctx["month"]["rows"]}
|
||||
assert m["coupang_rocket"]["roas"] == 300 and m["naver"]["roas"] is None and ctx["month"]["total"]["roas"] == 1000
|
||||
assert ctx["year"]["rows"][9]["roas"] == 1000 and ctx["year"]["rows"][10]["roas"] is None # 11월 = 앞으로
|
||||
assert ctx["roas_basis"]["google"] == "" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
|
||||
assert {r["code"]: r for r in ctx["month"]["rows"]}["google"]["roas"] is None
|
||||
assert ads.roas(1, 3) == 33 and ads.roas(1, 200) == 1 and ads.roas(5, 0) is None # 0.5% 반올림 → 1
|
||||
assert ctx["nav"]["quick"][2]["active"] # 이번달
|
||||
|
||||
|
||||
def test_ad_dashboard_year_and_missing_table():
|
||||
ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
rows = {r["label"]: r for r in ctx["table"]}
|
||||
assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000
|
||||
assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음
|
||||
miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0
|
||||
|
||||
|
||||
def test_ad_spend_endpoints(monkeypatch):
|
||||
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
|
||||
칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503."""
|
||||
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 Store:
|
||||
def __init__(self):
|
||||
self.saved, self.missing = [], False
|
||||
|
||||
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||
self.report = (roas, metrics)
|
||||
if self.missing:
|
||||
raise ads.AdMigrationNeeded()
|
||||
self.saved.extend((code, d, a, source) for d, a in entries)
|
||||
return len(entries)
|
||||
|
||||
def set_ad_spend(self, code, day, amount, *, source="manual", user=""):
|
||||
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||
|
||||
store = Store()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12"
|
||||
assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload")
|
||||
store.saved.clear()
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=coupang_wing", files={"file": ("w.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||
assert r.status_code == 200 and r.json()["name"] == "쿠팡(윙)" # 윙도 같은 양식
|
||||
assert store.saved[0] == ("coupang_wing", date(2026, 10, 1), 220000, "upload") and len(store.saved) == 3
|
||||
store.saved.clear()
|
||||
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n"
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))})
|
||||
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")})
|
||||
assert r.status_code == 400 and "양식" in r.json()["detail"]
|
||||
|
||||
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000
|
||||
assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200
|
||||
assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")]
|
||||
assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404
|
||||
assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400
|
||||
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400
|
||||
store.missing = True
|
||||
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1})
|
||||
assert r.status_code == 503 and "005" in r.json()["detail"]
|
||||
|
||||
# 사용자 제공 네이버 광고 보고서(2026-10-14) — 앞 9줄 + 머리글
|
||||
NAVER_CSV = """광고 계정 이름,광고 계정 ID,기간,총비용,노출수,클릭수,클릭률(%),총 전환수,구매완료 수,장바구니 담기 수,총 전환매출액,구매완료 광고수익률(%)
|
||||
0_미라네주방,38461,2026.09.30.,0,0,0,0.00,46,6,40,8218000,0.00
|
||||
0_미라네주방,38461,2026.09.24.,0,0,0,0.00,36,6,30,6331500,0.00
|
||||
0_미라네주방,38461,2026.09.23.,300672,30043,461,1.53,71,13,58,7830100,67.58
|
||||
0_미라네주방,38461,2026.09.22.,299817,31061,441,1.42,125,20,105,15040200,198.79
|
||||
0_미라네주방,38461,2026.09.21.,299199,25641,416,1.62,159,44,115,19878020,501.11
|
||||
"""
|
||||
|
||||
|
||||
def test_naver_report_reads_date_cost_roas_and_metrics():
|
||||
for content, name in ((NAVER_CSV.encode("utf-8-sig"), "n.csv"), (NAVER_CSV.encode("cp949"), "n.csv"), (_xlsx(NAVER_CSV), "n.xlsx")):
|
||||
res = ads.parse_naver(content, today=TODAY, filename=name)
|
||||
assert not res.errors, res.errors
|
||||
assert res.entries[:3] == [(date(2026, 9, 30), 0), (date(2026, 9, 24), 0), (date(2026, 9, 23), 300672)]
|
||||
assert str(res.roas[date(2026, 9, 23)]) == "67.58" and res.roas[date(2026, 9, 30)] == 0
|
||||
m = res.metrics[date(2026, 9, 21)]
|
||||
assert m["노출수"] == 25641 and m["클릭률(%)"] == 1.62 and m["총 전환매출액"] == 19878020
|
||||
assert m["구매완료 광고수익률(%)"] == 501.11 and "광고 계정 이름" not in m and "기간" not in m
|
||||
assert res.columns[0] == "총비용" and res.columns[-1] == "구매완료 광고수익률(%)"
|
||||
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
|
||||
bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n"
|
||||
errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors)
|
||||
assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs
|
||||
|
||||
|
||||
def test_naver_roas_from_report_weighted():
|
||||
"""네이버 칸 ROAS = 보고서 값(계산 안 함), 여러 날 = Σ(ROAS×광고비)÷Σ광고비, 광고비 0 인 날은 빼고."""
|
||||
class S(_Store):
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {(date(2026, 9, 22), "naver"): 299817, (date(2026, 9, 23), "naver"): 300672,
|
||||
(date(2026, 9, 24), "naver"): 0}
|
||||
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
return rows, {k: "upload" for k in rows}
|
||||
|
||||
def ad_roas(self, start, end):
|
||||
rows = {(date(2026, 9, 22), "naver"): Decimal("198.79"), (date(2026, 9, 23), "naver"): Decimal("67.58"),
|
||||
(date(2026, 9, 24), "naver"): Decimal("0")}
|
||||
return {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
return {(date(2026, 9, 22), "naver"): 9_999_999} if "naver" in codes else {}
|
||||
|
||||
ctx = ads.build_ad_dashboard(S(), kind="week", anchor=date(2026, 9, 23), today=TODAY, sales_codes=["naver"])
|
||||
by = {r.get("date"): r for r in ctx["table"]}
|
||||
assert by["2026-09-22"]["roas"]["naver"] == 199 and by["2026-09-23"]["roas"]["naver"] == 68
|
||||
assert by["2026-09-24"]["roas"]["naver"] is None # 광고비 0
|
||||
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||
want = round((Decimal("198.79") * 299817 + Decimal("67.58") * 300672) / (299817 + 300672))
|
||||
assert week["roas"]["naver"] == want == 133 # 매출 실적(9,999,999)으로 계산하지 않음
|
||||
assert ctx["roas_basis"]["naver"] == ""
|
||||
assert {r["code"]: r for r in ctx["month"]["rows"]}["naver"]["roas"] == 133
|
||||
|
||||
|
||||
def test_naver_detail_table_totals():
|
||||
rows = [{"date": "2026-09-22", "amount": 299817, "roas": Decimal("198.79"),
|
||||
"metrics": {"총비용": 299817, "노출수": 31061, "클릭수": 441, "클릭률(%)": 1.42, "구매완료 광고수익률(%)": 198.79}},
|
||||
{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"),
|
||||
"metrics": {"총비용": 300672, "노출수": 30043, "클릭수": 461, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 67.58}},
|
||||
{"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0,
|
||||
"클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}]
|
||||
t = ads.detail_table(rows)
|
||||
assert t["columns"] == ["총비용", "노출수", "클릭수", "클릭률(%)", "구매완료 광고수익률(%)"]
|
||||
assert t["total"]["총비용"] == 600489 and t["total"]["노출수"] == 61104 and t["total"]["클릭수"] == 902
|
||||
assert t["total"]["클릭률(%)"] == round(902 * 100 / 61104, 2) # 가중: 클릭수 ÷ 노출수
|
||||
assert t["total"]["구매완료 광고수익률(%)"] == 133.09 # 광고비 가중 평균 (198.79×299,817 + 67.58×300,672) ÷ 600,489
|
||||
assert t["rows"][0]["values"]["노출수"] == 31061 and t["rows"][1]["roas"] == 67.58
|
||||
|
||||
|
||||
def test_naver_upload_and_details_endpoints(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 Store:
|
||||
def __init__(self):
|
||||
self.saved, self.kw, self.missing = [], {}, ""
|
||||
|
||||
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||
if self.missing:
|
||||
raise ads.AdMigrationNeeded(self.missing)
|
||||
self.saved.extend((code, d, a, source) for d, a in entries)
|
||||
self.kw = {"roas": roas, "metrics": metrics}
|
||||
return len(entries)
|
||||
|
||||
def ad_details(self, code, start, end):
|
||||
if self.missing:
|
||||
raise ads.AdMigrationNeeded(self.missing)
|
||||
return [{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), "metrics": {"노출수": 30043}}]
|
||||
|
||||
store = Store()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8-sig"))})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["saved"] == 5 and r.json()["total"] == 300672 + 299817 + 299199
|
||||
assert store.saved[2] == ("naver", date(2026, 9, 23), 300672, "upload")
|
||||
assert str(store.kw["roas"][date(2026, 9, 23)]) == "67.58" and store.kw["metrics"][date(2026, 9, 21)]["클릭수"] == 416
|
||||
store.saved.clear()
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||
assert r.status_code == 200 and store.kw == {"roas": None, "metrics": None} # 쿠팡은 금액만
|
||||
d = client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()
|
||||
assert d["name"] == "네이버" and d["columns"] == ["노출수"] and d["rows"][0]["roas"] == 67.58
|
||||
assert client.get("/performance/api/ad-spend/coupang_rocket/details?from=2026-09-01&to=2026-09-30").status_code == 400
|
||||
assert client.get("/performance/api/ad-spend/naver/details?from=2026-09-30&to=2026-09-01").status_code == 400
|
||||
store.missing = "006"
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8"))})
|
||||
assert r.status_code == 503 and "006" in r.json()["detail"]
|
||||
assert "006" in client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()["detail"]
|
||||
|
||||
|
||||
def test_merge_results_newest_file_wins():
|
||||
"""여러 파일 — 같은 날짜는 파일 날짜(수정 시각)가 최신인 파일 값, 같으면 나중 파일. ROAS·상세도 그 파일 것."""
|
||||
a = ads.ParseResult(entries=[(date(2026, 9, 1), 100), (date(2026, 9, 2), 200)],
|
||||
roas={date(2026, 9, 2): Decimal("10")}, metrics={date(2026, 9, 2): {"노출수": 1}}, columns=["노출수"])
|
||||
b = ads.ParseResult(entries=[(date(2026, 9, 2), 999), (date(2026, 9, 3), 300)],
|
||||
roas={date(2026, 9, 2): Decimal("99")}, metrics={date(2026, 9, 2): {"노출수": 9}}, columns=["노출수", "클릭수"])
|
||||
m, overlap = ads.merge_results([("new.csv", 2000.0, a), ("old.csv", 1000.0, b)]) # a 가 최신
|
||||
assert m.entries == [(date(2026, 9, 1), 100), (date(2026, 9, 2), 200), (date(2026, 9, 3), 300)]
|
||||
assert m.roas[date(2026, 9, 2)] == Decimal("10") and m.metrics[date(2026, 9, 2)] == {"노출수": 1}
|
||||
assert overlap == [date(2026, 9, 2)] and m.columns == ["노출수", "클릭수"]
|
||||
m2, _ = ads.merge_results([("a.csv", 1000.0, a), ("b.csv", 1000.0, b)]) # 같은 시각 → 나중 파일
|
||||
assert dict(m2.entries)[date(2026, 9, 2)] == 999
|
||||
bad = ads.ParseResult(errors=["3행: 오류"])
|
||||
m3, _ = ads.merge_results([("a.csv", 1.0, a), ("bad.csv", 2.0, bad)])
|
||||
assert m3.errors == ["[bad.csv] 3행: 오류"]
|
||||
|
||||
|
||||
def test_upload_multiple_files_endpoint(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 Store:
|
||||
saved: list = []
|
||||
|
||||
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||
self.saved = list(entries)
|
||||
self.roas = roas
|
||||
return len(entries)
|
||||
|
||||
store = Store()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
old = NAVER_CSV
|
||||
new = NAVER_CSV.replace("2026.09.23.,300672", "2026.09.23.,111111").replace(",67.58", ",12.34")
|
||||
files = [("files", ("new.csv", new.encode("utf-8"))), ("files", ("old.csv", old.encode("utf-8")))]
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["2000", "1000"]})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["files"] == 2 and body["overlap_days"] == 5 and body["saved"] == 5
|
||||
assert dict(store.saved)[date(2026, 9, 23)] == 111111 and str(store.roas[date(2026, 9, 23)]) == "12.34" # 최신 파일
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["1000", "2000"]})
|
||||
assert dict(store.saved)[date(2026, 9, 23)] == 300672 # 이번엔 old 가 최신
|
||||
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver",
|
||||
files=[("files", ("ok.csv", old.encode("utf-8"))), ("files", ("bad.csv", bad.encode("utf-8")))])
|
||||
assert r.status_code == 400 and r.json()["errors"][0].startswith("[bad.csv]")
|
||||
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("one.csv", old.encode("utf-8"))})
|
||||
assert r.status_code == 200 and r.json()["files"] == 1 # 예전 file 한 개도
|
||||
assert client.post("/performance/api/ad-spend/upload?channel=naver").status_code in (400, 422)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from app.modules.performance import auto_sync as au
|
||||
|
||||
KST = timezone(timedelta(hours=9))
|
||||
H = (9, 19)
|
||||
|
||||
|
||||
def _t(h, m, d=13):
|
||||
return datetime(2026, 10, d, h, m, tzinfo=KST)
|
||||
|
||||
|
||||
def test_slots_every_half_hour_9_to_19():
|
||||
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
|
||||
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
|
||||
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
|
||||
|
||||
|
||||
def test_next_slot():
|
||||
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
|
||||
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
|
||||
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
|
||||
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
|
||||
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
|
||||
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
|
||||
|
||||
|
||||
def test_env_parsing(monkeypatch):
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
|
||||
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
|
||||
assert au.hour_window() == (8, 20)
|
||||
|
||||
|
||||
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||
from app.modules.performance import jobs
|
||||
from app.modules.performance.sync import SyncService
|
||||
|
||||
calls = []
|
||||
|
||||
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
|
||||
calls.append((start, end, trigger, user, job is not None))
|
||||
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
|
||||
|
||||
class Store:
|
||||
def last_update_at(self):
|
||||
return "2026-10-13T09:00:05+09:00"
|
||||
|
||||
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
|
||||
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""}
|
||||
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||
assert len(calls) == 1
|
||||
@@ -0,0 +1,91 @@
|
||||
"""쿠팡 발주서 — 504(시간 초과)면 조회 구간을 반으로 줄여 다시 부른다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||
|
||||
|
||||
class Creds:
|
||||
def get(self, key):
|
||||
return {"vendor_id": "A001", "access_key": "ak", "secret_key": "sk"}[key]
|
||||
|
||||
def has(self, key):
|
||||
return True
|
||||
|
||||
|
||||
def _ctx():
|
||||
return AdapterContext(code="coupang", credentials=Creds())
|
||||
|
||||
|
||||
def _days(params):
|
||||
a = date.fromisoformat(params["createdAtFrom"][:10])
|
||||
b = date.fromisoformat(params["createdAtTo"][:10])
|
||||
return a, b
|
||||
|
||||
|
||||
def test_seller_window_halves_on_timeout_and_remembers(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
a, b = _days(params)
|
||||
calls.append((params["status"], a, b))
|
||||
if params["status"] == "FINAL_DELIVERY" and (b - a).days + 1 > 7:
|
||||
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||
return [{"orderId": f"{params['status']}-{a}-{b}"}]
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
ad = cp.CoupangAdapter()
|
||||
start, end = date(2026, 1, 1), date(2026, 3, 31) # 주문일 2025-12-31 ~ 3-31 = 91일 → 31일 구간 3개
|
||||
ad._seller_orders(_ctx(), start, end)
|
||||
|
||||
fd = [(a, b) for st, a, b in calls if st == "FINAL_DELIVERY"]
|
||||
ok = [(a, b) for a, b in fd if (b - a).days + 1 <= 7]
|
||||
# 성공한 구간이 빈틈·겹침 없이 전체 주문일을 덮는다
|
||||
d = start - timedelta(days=1)
|
||||
for a, b in ok:
|
||||
assert a == d
|
||||
d = b + timedelta(days=1)
|
||||
assert d == end + timedelta(days=1)
|
||||
# 31 → 15 → 7 로 줄인 뒤엔 다음 31일 구간도 처음부터 7일로(실패는 첫 구간의 두 번뿐)
|
||||
assert len(fd) - len(ok) == 2
|
||||
# 다른 상태는 31일 그대로
|
||||
assert sum(1 for st, a, b in calls if st == "ACCEPT") == 3
|
||||
|
||||
|
||||
def test_one_day_timeout_retries_then_fails(monkeypatch):
|
||||
sleeps = []
|
||||
monkeypatch.setattr(cp.time, "sleep", lambda s: sleeps.append(s))
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
if params["status"] == "FINAL_DELIVERY":
|
||||
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
with pytest.raises(ApiError) as ei:
|
||||
cp.CoupangAdapter()._seller_orders(_ctx(), date(2026, 1, 5), date(2026, 1, 5))
|
||||
assert "하루도 시간 초과" in ei.value.message and "FINAL_DELIVERY" in ei.value.message
|
||||
assert sleeps == [3.0, 6.0]
|
||||
|
||||
|
||||
def test_rg_window_halves_on_timeout(monkeypatch):
|
||||
got = []
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
a = date(int(params["paidDateFrom"][:4]), int(params["paidDateFrom"][4:6]), int(params["paidDateFrom"][6:]))
|
||||
b = date(int(params["paidDateTo"][:4]), int(params["paidDateTo"][4:6]), int(params["paidDateTo"][6:]))
|
||||
if (b - a).days + 1 > 10:
|
||||
raise cp.GatewayTimeout("쿠팡 로켓그로스 주문 API 오류(504)")
|
||||
got.append((a, b))
|
||||
return [{"orderId": str(a)}]
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
cp.CoupangAdapter()._rg_orders(_ctx(), date(2026, 1, 1), date(2026, 1, 30))
|
||||
assert got[0][0] == date(2026, 1, 1) and got[-1][1] == date(2026, 1, 30)
|
||||
assert all((b - a).days + 1 <= 10 for a, b in got)
|
||||
assert all(got[i + 1][0] == got[i][1] + timedelta(days=1) for i in range(len(got) - 1))
|
||||
@@ -0,0 +1,143 @@
|
||||
"""수동 입력 엑셀 업로드 — 머리글 매칭·값 있는 칸만·오류 시 전부 거절."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.modules.performance import manual_upload as mu
|
||||
|
||||
TODAY = date(2026, 10, 13)
|
||||
MARKETS = [
|
||||
{"code": "naver", "name": "네이버", "manual_input": False},
|
||||
{"code": "coupang_rocket", "name": "쿠팡(로켓)", "manual_input": True},
|
||||
{"code": "ohouse", "name": "오늘의집", "manual_input": True},
|
||||
{"code": "toss", "name": "토스쇼핑", "manual_input": True},
|
||||
{"code": "atomy", "name": "애터미아자몰", "manual_input": True},
|
||||
]
|
||||
EXTRA = {"toss": ("토스쇼핑", "토스")}
|
||||
|
||||
|
||||
def _xlsx(rows):
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
for r in rows:
|
||||
ws.append(list(r))
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _parse(rows):
|
||||
return mu.parse_workbook(_xlsx(rows), markets=MARKETS, today=TODAY, extra_names=EXTRA)
|
||||
|
||||
|
||||
def test_only_filled_cells_of_manual_shops():
|
||||
res = _parse([
|
||||
("날짜", "쿠팡(로켓)", " 오늘의 집 ", "네이버", "모르는몰", "토스", "애터미아자몰"),
|
||||
(datetime(2026, 10, 12), 1_000, None, 999, 5, "12,300원", ""),
|
||||
("2026.10.13(화)", None, 0, None, None, None, 4500.4),
|
||||
(None, None, None, None, None, None, None), # 빈 줄
|
||||
])
|
||||
assert not res.errors
|
||||
assert res.columns == ["coupang_rocket", "ohouse", "toss", "atomy"]
|
||||
assert sorted(res.entries) == sorted([
|
||||
("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 12), 12300),
|
||||
("ohouse", date(2026, 10, 13), 0), ("atomy", date(2026, 10, 13), 4500)])
|
||||
assert res.ignored == ["네이버(수동 입력 꺼짐)", "모르는몰(알 수 없는 쇼핑몰)"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expect", [
|
||||
("2026-10-01", date(2026, 10, 1)), ("2026/10/1", date(2026, 10, 1)), ("20261001", date(2026, 10, 1)),
|
||||
(20261001, date(2026, 10, 1)), (46296, date(2026, 10, 1)), ("2026년 10월 1일", date(2026, 10, 1)), (None, None),
|
||||
])
|
||||
def test_parse_date(raw, expect):
|
||||
assert mu.parse_date(raw) == expect
|
||||
|
||||
|
||||
def test_errors_reject_everything_with_cell_refs():
|
||||
res = _parse([
|
||||
("날짜", "쿠팡(로켓)", "오늘의집"),
|
||||
("2026-10-10", "abc", 100),
|
||||
("엉터리", 1, None),
|
||||
("2026-10-14", 1, None), # 앞으로의 날짜
|
||||
(None, 5, None), # 날짜 없음
|
||||
("2026-10-11", 7, None),
|
||||
("2026-10-11", 8, None), # 같은 날 두 번
|
||||
])
|
||||
joined = "\n".join(res.errors)
|
||||
assert "B2" in joined and "A3" in joined and "A4" in joined and "5행" in joined and "B7" in joined
|
||||
assert len(res.errors) == 5
|
||||
|
||||
|
||||
def test_header_problems():
|
||||
with pytest.raises(mu.UploadError):
|
||||
_parse([("날짜", "네이버", "모르는몰"), ("2026-10-10", 1, 2)]) # 반영할 열 없음
|
||||
with pytest.raises(mu.UploadError):
|
||||
mu.parse_workbook(b"not an xlsx", markets=MARKETS, today=TODAY)
|
||||
res = _parse([("날짜", "쿠팡(로켓)", "coupang_rocket"), ("2026-10-10", 1, 2)])
|
||||
assert any("두 번" in e for e in res.errors)
|
||||
|
||||
|
||||
def test_sample_file_headers_match_marketplaces():
|
||||
"""모듈 폴더 샘플 파일 머리글 = 수동 입력 쇼핑몰 이름(시드 기준) — 업로드하면 전부 반영 대상이어야 한다."""
|
||||
sample = Path(mu.__file__).resolve().parent / "upload_sample.xlsx"
|
||||
seed = [{"code": c, "name": n, "manual_input": True} for c, n in (
|
||||
("coupang_rocket", "쿠팡(로켓)"), ("ohouse", "오늘의집"), ("gmarket", "G마켓"), ("kakao", "카카오"),
|
||||
("gsshop", "GS샵"), ("lotteon", "롯데ON"), ("atomy", "애터미아자몰"))]
|
||||
wb = openpyxl.load_workbook(sample)
|
||||
ws = wb.active
|
||||
ws.append([date(2026, 10, 1)] + [1] * 7)
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
res = mu.parse_workbook(buf.getvalue(), markets=seed, today=TODAY)
|
||||
assert not res.errors and not res.ignored and len(res.entries) == 7
|
||||
|
||||
|
||||
def test_upload_endpoint_saves_or_rejects(monkeypatch):
|
||||
"""라우터: 정상 파일은 한 번에 저장, 잘못된 칸이 있으면 400 + 칸 목록, 아무것도 저장 안 함. 샘플 받기."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import importlib
|
||||
|
||||
from app.modules.performance import common
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router") # 패키지 속성 router 는 APIRouter
|
||||
|
||||
class Store:
|
||||
saved: list = []
|
||||
|
||||
def list_marketplaces(self):
|
||||
return [{**m, "enabled": True} for m in MARKETS]
|
||||
|
||||
def set_manual_sales_bulk(self, entries, *, user=""):
|
||||
self.saved.extend(entries)
|
||||
return len(entries)
|
||||
|
||||
store = Store()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
ok = _xlsx([("날짜", "쿠팡(로켓)", "토스"), ("2026-10-12", 1000, None), ("2026-10-13", None, 2000)])
|
||||
r = client.post("/performance/api/manual-sales/upload", files={"file": ("a.xlsx", ok)})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["saved"] == 2 and body["from"] == "2026-10-12" and body["to"] == "2026-10-13"
|
||||
assert [s["code"] for s in body["by_shop"]] == ["coupang_rocket", "toss"]
|
||||
assert sorted(store.saved) == [("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 13), 2000)]
|
||||
|
||||
store.saved.clear()
|
||||
bad = _xlsx([("날짜", "쿠팡(로켓)"), ("2026-10-12", 1000), ("2026-10-13", "x")])
|
||||
r = client.post("/performance/api/manual-sales/upload", files={"file": ("b.xlsx", bad)})
|
||||
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||
|
||||
r = client.get("/performance/api/manual-sales/sample.xlsx")
|
||||
assert r.status_code == 200 and r.content[:2] == b"PK"
|
||||
@@ -1064,15 +1064,18 @@ def test_coupang_hmac_and_connection_errors():
|
||||
seen = {}
|
||||
|
||||
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
||||
seen.setdefault("urls", []).append(url)
|
||||
seen["url"], seen["auth"] = url, headers["Authorization"]
|
||||
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
||||
|
||||
orig = httpx.get
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
try:
|
||||
httpx.get = fake_get
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = fake_get, 0, 0
|
||||
msg = cp.CoupangAdapter().test_connection(ctx)
|
||||
assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
|
||||
assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
|
||||
first, rg = seen["urls"]
|
||||
assert "연결 정상" in msg and "로켓그로스" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in first
|
||||
assert "%2B09:00" in first and "SK-SECRET" not in seen["auth"]
|
||||
assert "/rg_open_api/apis/api/v1/vendors/A00012345/rg/orders?paidDateFrom=" in rg
|
||||
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
||||
try:
|
||||
cp.CoupangAdapter().test_connection(ctx)
|
||||
@@ -1081,7 +1084,158 @@ def test_coupang_hmac_and_connection_errors():
|
||||
else:
|
||||
raise AssertionError("403 이면 인증 실패여야 합니다")
|
||||
finally:
|
||||
httpx.get = orig
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
|
||||
|
||||
def _cp_sheet(order_id, box, paid, items, *, status="INSTRUCT", ship=3000):
|
||||
def money(n):
|
||||
return {"currencyCode": "KRW", "units": n, "nanos": 0}
|
||||
|
||||
return {"shipmentBoxId": box, "orderId": order_id, "orderedAt": paid, "paidAt": paid, "status": status,
|
||||
"orderer": {"name": "홍길동", "safeNumber": "0502-1111-2222"},
|
||||
"receiver": {"name": "홍길동", "addr1": "서울 비밀구 1", "receiverNumber": "+82-10-1234-5678"},
|
||||
"parcelPrintMessage": "문 앞", "shippingPrice": money(ship), "remotePrice": money(0),
|
||||
"orderItems": [{"sequenceNo": f"{i + 1:03d}", "vendorItemId": 100 + i, "vendorItemName": n,
|
||||
"sellerProductName": n, "sellerProductItemName": "1개", "shippingCount": q,
|
||||
"salesPrice": money(p), "orderPrice": money(p * q), "discountPrice": money(dc),
|
||||
"cancelCount": cc, "holdCountForCancel": 0, "canceled": cc >= q,
|
||||
"etcInfoValues": ["개인 메모"]}
|
||||
for i, (n, p, q, dc, cc) in enumerate(items)]}
|
||||
|
||||
|
||||
def _cp_rg(order_id, paid_ms, items):
|
||||
return {"vendorId": "A00012345", "orderId": order_id, "paidAt": paid_ms,
|
||||
"orderItems": [{"vendorItemId": 900 + i, "productName": n, "salesQuantity": q, "unitSalesPrice": str(p),
|
||||
"currency": "KRW"} for i, (n, p, q) in enumerate(items)]}
|
||||
|
||||
|
||||
def _cp_server(sheets_by_status, rg_pages):
|
||||
"""가짜 쿠팡 — 발주서는 상태별 목록(2쪽까지), 로켓그로스는 nextToken 쪽 넘김. 호출 기록을 남긴다."""
|
||||
import httpx
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
calls = []
|
||||
|
||||
def get(url, headers=None, timeout=None):
|
||||
u = urlparse(url)
|
||||
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||
calls.append((u.path, q))
|
||||
if u.path.endswith("/rg/orders"):
|
||||
i = int(q.get("nextToken") or 0)
|
||||
nxt = str(i + 1) if i + 1 < len(rg_pages) else ""
|
||||
return httpx.Response(200, json={"code": 200, "message": "SUCCESS", "data": rg_pages[i], "nextToken": nxt})
|
||||
rows = sheets_by_status.get(q["status"], [])
|
||||
if q.get("nextToken") == "p2":
|
||||
return httpx.Response(200, json={"code": 200, "data": rows[1:], "nextToken": ""})
|
||||
return httpx.Response(200, json={"code": 200, "data": rows[:1], "nextToken": "p2" if len(rows) > 1 else ""})
|
||||
|
||||
return get, calls
|
||||
|
||||
|
||||
KST_1012_0030_MS = 1791732600000 # 2026-10-12 00:30 KST = 10-11 15:30 UTC
|
||||
|
||||
|
||||
def test_coupang_collect_sales():
|
||||
"""쿠팡 매출 = 판매자배송 발주서 orderPrice(쿠폰 할인 전) + 로켓그로스 단가 × 수량, 결제일(한국 시간) 기준.
|
||||
상태 6개 모두 조회·쪽 넘김, 결제일이 기간 밖이면 뺌, 결제 뒤 취소된 줄도 결제일 매출, 같은 발주서 두 번 와도 한 번.
|
||||
구매자·수령자 정보는 저장하지 않는다."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
|
||||
sheets = {
|
||||
"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0), ("뚜껑", 3000, 1, 0, 0)]),
|
||||
_cp_sheet(2, 21, "2026-10-12T23:59:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])], # 결제 뒤 취소
|
||||
"FINAL_DELIVERY": [_cp_sheet(3, 31, "2026-10-11T23:50:00+09:00", [("밀폐용기", 12000, 1, 0, 0)]), # 전날 결제 — 뺌
|
||||
_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)])], # 같은 발주서 다시
|
||||
}
|
||||
rg_pages = [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])], [_cp_rg(71, KST_1012_0030_MS + 3600_000, [("컵", 5000, 1)])]]
|
||||
get, calls = _cp_server(sheets, rg_pages)
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "coupang"),
|
||||
{"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-SECRET"})
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||
try:
|
||||
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||
finally:
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
assert r["ok"], r
|
||||
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "coupang"}
|
||||
assert set(ev_) == {"coupang:1", "coupang:2", "coupang:rg:70", "coupang:rg:71"}, set(ev_)
|
||||
assert ev_["coupang:1"]["amount"] == 24000 + 3000 and ev_["coupang:1"]["quantity"] == 3 # 배송비 제외, 중복 없음
|
||||
assert ev_["coupang:1"]["discount_amount"] == 1000 and ev_["coupang:1"]["product_name"] == "밀폐용기 외 1건"
|
||||
assert ev_["coupang:2"]["amount"] == 12000 and "취소" in ev_["coupang:2"]["order_status"]
|
||||
assert ev_["coupang:rg:70"]["amount"] == 29700 and ev_["coupang:rg:70"]["sales_date"] == date(2026, 10, 12)
|
||||
assert ev_["coupang:rg:71"]["amount"] == 5000 # 다음 쪽(nextToken)
|
||||
assert {q["status"] for p, q in calls if p.endswith("/ordersheets")} == set(cp.STATUSES)
|
||||
sheet_q = next(q for p, q in calls if p.endswith("/ordersheets"))
|
||||
assert sheet_q["createdAtFrom"] == "2026-10-11+09:00" and sheet_q["createdAtTo"] == "2026-10-12+09:00" # 주문일 하루 앞부터
|
||||
assert any(q.get("nextToken") == "p2" and q["status"] == "INSTRUCT" for p, q in calls if p.endswith("/ordersheets"))
|
||||
rg_q = next(q for p, q in calls if p.endswith("/rg/orders"))
|
||||
assert rg_q["paidDateFrom"] == "20261012" and rg_q["paidDateTo"] == "20261012"
|
||||
assert "홍길동" not in repr(st.events) and "비밀구" not in repr(st.events) and "1234-5678" not in repr(st.events)
|
||||
|
||||
|
||||
def test_coupang_spans_and_money():
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
|
||||
assert cp.spans(date(2026, 1, 1), date(2026, 3, 5), 31) == [
|
||||
(date(2026, 1, 1), date(2026, 1, 31)), (date(2026, 2, 1), date(2026, 3, 3)), (date(2026, 3, 4), date(2026, 3, 5))]
|
||||
assert cp._won({"units": 15000, "nanos": 0}) == 15000 and cp._won("27,800") == 27800 and cp._won(None) == 0
|
||||
assert cp._kst_day("2026-10-12T00:10:00+09:00") == date(2026, 10, 12)
|
||||
assert cp._kst_day("2026-10-11T15:10:00Z") == date(2026, 10, 12) # UTC → 한국 날짜
|
||||
assert cp._kst_day(KST_1012_0030_MS) == date(2026, 10, 12)
|
||||
assert cp._kst_day("2026-10-12") == date(2026, 10, 12) and cp._kst_day("") is None
|
||||
|
||||
|
||||
def test_coupang_reconcile_candidates_hide_personal():
|
||||
"""원본 데이터 확인 — 날짜별 후보 금액(할인 전·후, 취소분 뺀 값, 로켓그로스)·판매량, 개인정보 항목은 아예 없음.
|
||||
로켓그로스만 실패해도 판매자배송 결과는 보여 준다."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
|
||||
class Creds(dict):
|
||||
def get(self, k, default=""):
|
||||
return dict.get(self, k, default)
|
||||
|
||||
def has(self, k):
|
||||
return bool(dict.get(self, k))
|
||||
|
||||
ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||
sheets = {"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)]),
|
||||
_cp_sheet(2, 21, "2026-10-13T10:00:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])]}
|
||||
get, _calls = _cp_server(sheets, [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])]])
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||
try:
|
||||
rec = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12), to=date(2026, 10, 13))
|
||||
cands = {c["label"][:1]: c for c in rec["refund_candidates"]}
|
||||
assert cands["①"]["days"] == {"2026-10-12": 24000 + 29700, "2026-10-13": 12000}
|
||||
assert cands["②"]["days"]["2026-10-12"] == 24000 and cands["③"]["days"]["2026-10-12"] == 23000
|
||||
assert cands["④"]["days"]["2026-10-13"] == 0 and cands["⑤"]["days"]["2026-10-12"] == 29700
|
||||
assert next(c for c in rec["refund_candidates"] if c["label"].startswith("판매량"))["days"]["2026-10-12"] == 5
|
||||
assert rec["days"][0] == {"date": "2026-10-12", "orders": 2, "amount": 53700, "claimed": 0, "ship": 3000}
|
||||
assert rec["days"][1]["claimed"] == 12000 and rec["candidates_title"]
|
||||
names = {f["name"] for p in rec["probes"] if p["ok"] for f in p["fields"]}
|
||||
assert "orderItems.orderPrice.units" in names and not any(n.startswith(("orderer", "receiver")) for n in names)
|
||||
assert "홍길동" not in repr(rec) and "비밀구" not in repr(rec) and "개인 메모" not in repr(rec) and "문 앞" not in repr(rec)
|
||||
|
||||
def deny_rg(url, headers=None, timeout=None): # 로켓그로스만 거부(403)
|
||||
if "/rg/orders" in url:
|
||||
return httpx.Response(403, json={"message": "Access Denied"})
|
||||
return get(url, headers, timeout)
|
||||
|
||||
httpx.get = deny_rg
|
||||
rec2 = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12))
|
||||
p = {x["key"]: x for x in rec2["probes"]}
|
||||
assert p["seller"]["ok"] and not p["rg"]["ok"] and "403" in p["rg"]["error"]
|
||||
assert rec2["refund_candidates"][0]["error"] and rec2["refund_candidates"][1]["days"]["2026-10-12"] == 24000
|
||||
finally:
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
|
||||
|
||||
def test_elevenst_connection():
|
||||
@@ -1224,10 +1378,15 @@ def test_elevenst_collect_sales():
|
||||
|
||||
def test_registry_and_event_validation():
|
||||
codes = [a.code for a in all_adapters()]
|
||||
assert len(codes) == len(set(codes)) == 10
|
||||
assert len(codes) == len(set(codes)) == 12
|
||||
assert codes == ["cafe24", "naver", "coupang", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||
for a in all_adapters():
|
||||
keys = [f.key for f in a.credential_fields()]
|
||||
assert len(keys) == len(set(keys)), a.code
|
||||
if a.manual_only: # 수동 입력 전용 — 인증 항목 없음
|
||||
assert not keys and not a.implemented, a.code
|
||||
continue
|
||||
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
||||
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
||||
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
||||
@@ -1613,6 +1772,158 @@ def test_gsshop_collect_sales():
|
||||
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
|
||||
|
||||
|
||||
def _kakao_detail(oid, pid, paid, price, qty=1, opt=0, sdc=0, cdc=0, adc=0, ship=3000, status="ShippingProgress"):
|
||||
return {"id": oid,
|
||||
"orderBase": {"id": oid, "paymentId": pid, "status": status, "createdAt": paid, "paidAt": paid,
|
||||
"modifiedAt": paid},
|
||||
"orderer": {"phoneNumber": "010-1234-5678"},
|
||||
"orderProduct": {"id": oid, "name": "미라클통", "optionContent": "3200ml", "quantity": qty,
|
||||
"productPrice": price, "optionPrice": opt, "sellerDiscountPrice": sdc,
|
||||
"sellerCouponDiscountPrice": cdc, "adminDiscountPrice": adc, "deliveryAmount": ship,
|
||||
"areaAdditionalDeliveryAmount": 0},
|
||||
"orderDeliveryRequest": {"receiverName": "홍길동", "receiverAddress1": "서울 반품동", "requirement": "문 앞"},
|
||||
"orderClaimReturn": {"claimItemStatus": "RETURN_COMPLETE", "pickupName": "홍길동", "reasonComment": "변심"}}
|
||||
|
||||
|
||||
def test_kakao_connection_headers_and_errors():
|
||||
"""카카오: kapi.kakao.com + Authorization(앱 어드민 키)·Target-Authorization(판매자 인증키)·channel-ids 헤더.
|
||||
-2(두 키가 같은 앱)·-401(판매자 키 무효)·403 은 인증 실패, 키 값은 메시지에 없음."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import kakao as kk
|
||||
from app.modules.performance.adapters.base import AdapterContext, NotConfigured
|
||||
|
||||
class Creds(dict):
|
||||
def get(self, k, default=""):
|
||||
return dict.get(self, k, default)
|
||||
|
||||
def has(self, k):
|
||||
return bool(dict.get(self, k))
|
||||
|
||||
ctx = AdapterContext(code="kakao", credentials=Creds(admin_key="ADMIN-SECRET", api_key="SELLER-SECRET"))
|
||||
seen = {}
|
||||
|
||||
def ok(url, params=None, headers=None, timeout=None):
|
||||
seen.update(url=url, params=params, headers=headers)
|
||||
return httpx.Response(200, json={"contents": [{"orderId": 1, "paymentId": 9, "orderStatus": "PayComplete"}]})
|
||||
|
||||
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||
kk.CALL_INTERVAL_SEC = 0
|
||||
try:
|
||||
httpx.get = ok
|
||||
msg = kk.KakaoAdapter().test_connection(ctx)
|
||||
assert "연결 정상" in msg and "1건" in msg
|
||||
assert seen["url"] == "https://kapi.kakao.com/v2/shopping/orders/paidAt"
|
||||
assert seen["headers"]["Authorization"] == "KakaoAK ADMIN-SECRET"
|
||||
assert seen["headers"]["Target-Authorization"] == "KakaoAK SELLER-SECRET"
|
||||
assert seen["headers"]["channel-ids"] == "101" # 기본 톡스토어
|
||||
assert seen["params"]["from"].endswith(" 00:00:00") and seen["params"]["to"].endswith(" 23:59:59")
|
||||
ctx2 = AdapterContext(code="kakao", credentials=Creds(admin_key="A", api_key="S", channel_ids=" 1, 101 "))
|
||||
kk.KakaoAdapter().test_connection(ctx2)
|
||||
assert seen["headers"]["channel-ids"] == "1,101"
|
||||
for status, body, kind, word in (
|
||||
(401, {"msg": "invalid authorization or target-authorization header.", "code": -2}, AuthFailed, "서로 다른 앱"),
|
||||
(401, {"msg": "appKey(판매자인증키) is already deactivated", "code": -401}, AuthFailed, "판매자 API 인증키"),
|
||||
(400, {"code": -800, "msg": "대행사 매핑/권한 확인이 필요합니다."}, AuthFailed, "연결되지 않았습니다"),
|
||||
(403, {"code": -3, "msg": "forbidden"}, AuthFailed, "403"),
|
||||
(500, {"code": -500, "msg": "internal"}, ApiError, "500")):
|
||||
httpx.get = (lambda s, b: lambda url, params=None, headers=None, timeout=None: httpx.Response(s, json=b))(status, body)
|
||||
try:
|
||||
kk.KakaoAdapter().test_connection(ctx)
|
||||
except kind as exc:
|
||||
assert word in exc.message and "ADMIN-SECRET" not in exc.message and "SELLER-SECRET" not in exc.message
|
||||
else:
|
||||
raise AssertionError("오류여야 합니다")
|
||||
finally:
|
||||
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||
try:
|
||||
kk.KakaoAdapter().test_connection(AdapterContext(code="kakao", credentials=Creds(api_key="S")))
|
||||
except NotConfigured:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("어드민 키 없으면 미설정")
|
||||
|
||||
|
||||
def test_kakao_collect_sales():
|
||||
"""카카오 매출 = 결제(paymentId) 하나, 결제일 기준, (상품가+옵션가)×수량 − 할인들, 배송비 제외.
|
||||
목록(paidAt, token 으로 다음 쪽) → 주문정보(order_id). 미결제는 빼고 결제 뒤 취소는 포함. 개인정보 미저장."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import kakao as kk
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
|
||||
details = {
|
||||
11: _kakao_detail(11, 900, "20261001101500", 10000, qty=2, opt=1000, sdc=500, cdc=1000, adc=500), # 22000-2000
|
||||
12: _kakao_detail(12, 900, "20261001101500", 5000), # 같은 결제
|
||||
13: _kakao_detail(13, 901, "20261001200000", 7000, status="PayCancelComplete"), # 결제 뒤 취소
|
||||
15: _kakao_detail(15, 903, "20261002090000", 3000),
|
||||
}
|
||||
rows = {
|
||||
"2026-10-01": [[{"orderId": 11, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||
"modifiedAt": "20261001110000"},
|
||||
{"orderId": 12, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||
"modifiedAt": "20261001110000"}],
|
||||
[{"orderId": 13, "paymentId": 901, "orderStatus": "PayCancelComplete", "paidAt": "20261001200000",
|
||||
"modifiedAt": "20261001210000"},
|
||||
{"orderId": 14, "paymentId": 902, "orderStatus": "PayWaiting", "paidAt": "",
|
||||
"modifiedAt": "20261001210000"}]],
|
||||
"2026-10-02": [[{"orderId": 15, "paymentId": 903, "orderStatus": "BuyDecision", "paidAt": "20261002090000",
|
||||
"modifiedAt": "20261002090000"}]],
|
||||
}
|
||||
calls = []
|
||||
|
||||
def get(url, params=None, headers=None, timeout=None):
|
||||
calls.append((url.rsplit("/", 1)[-1], dict(params)))
|
||||
if url.endswith("/v1/shopping/order"):
|
||||
return httpx.Response(200, json=details[int(params["order_id"])])
|
||||
pages = rows.get(params["from"][:10], [[]])
|
||||
i = int(params.get("token") or 0)
|
||||
body = {"contents": pages[i]}
|
||||
if i + 1 < len(pages):
|
||||
body["token"] = str(i + 1)
|
||||
return httpx.Response(200, json=body)
|
||||
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "kakao"), {"admin_key": "ADMIN", "api_key": "SELLER"})
|
||||
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||
try:
|
||||
r = SyncService(st, creds).sync_marketplace("kakao", date(2026, 10, 1), date(2026, 10, 2))
|
||||
finally:
|
||||
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||
assert r["ok"], r
|
||||
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "kakao"}
|
||||
assert set(ev_) == {"kakao:900", "kakao:901", "kakao:903"} # 미결제 902 제외
|
||||
a = ev_["kakao:900"]
|
||||
assert a["amount"] == (10000 + 1000) * 2 - 2000 + 5000 and a["sales_date"] == date(2026, 10, 1)
|
||||
assert a["discount_amount"] == 2000 and a["quantity"] == 3 and a["product_name"] == "미라클통"
|
||||
assert ev_["kakao:901"]["amount"] == 7000 # 결제 뒤 취소도 결제일 매출(네이버와 같은 기준)
|
||||
assert ev_["kakao:903"]["sales_date"] == date(2026, 10, 2)
|
||||
assert not any(c[0] == "order" and c[1]["order_id"] == "14" for c in calls) # 미결제는 주문정보도 안 부름
|
||||
assert [c[1].get("token") for c in calls if c[0] == "paidAt"] == [None, "1", None] # 다음 쪽 token
|
||||
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||
|
||||
# 원본 데이터 확인 — 개인정보는 값 없이 이름만, 날짜별 현재 규칙 매출
|
||||
ad = kk.KakaoAdapter()
|
||||
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||
try:
|
||||
rec = ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1),
|
||||
to=date(2026, 10, 2))
|
||||
n = len(calls)
|
||||
ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1))
|
||||
assert not [c for c in calls[n:] if c[0] == "order"] # 수정일이 같으면 주문정보 캐시
|
||||
finally:
|
||||
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||
assert rec["days"][0] == {"date": "2026-10-01", "orders": 2, "amount": 25000 + 7000, "claimed": 7000, "ship": 9000}
|
||||
assert rec["days"][1]["amount"] == 3000
|
||||
f = {x["name"]: x for x in rec["probes"][0]["fields"]}
|
||||
assert f["orderProduct.productPrice"]["sum"] == 10000 + 5000 + 7000 + 3000
|
||||
assert f["orderDeliveryRequest.receiverName"]["sample"] == "" and f["orderer.phoneNumber"]["sample"] == ""
|
||||
assert "홍길동" not in repr(rec) and "반품동" not in repr(rec) and "010-1234-5678" not in repr(rec)
|
||||
assert "변심" not in repr(rec) and "문 앞" not in repr(rec)
|
||||
|
||||
|
||||
def test_sync_job_cancel():
|
||||
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
|
||||
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
|
||||
@@ -1720,6 +2031,21 @@ def test_sync_job_stop_shop():
|
||||
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
||||
|
||||
|
||||
def test_manual_only_marketplaces_skip_sync_and_show_manual_status():
|
||||
"""쿠팡(로켓)·애터미아자몰 = 수동 입력 전용 — 매출 업데이트 대상이 아니고 연결 상태는 "수동 입력"."""
|
||||
from app.modules.performance.dashboard import display_status
|
||||
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
res = SyncService(st, creds).sync_all(start=date(2026, 10, 1), end=date(2026, 10, 2),
|
||||
codes=["coupang_rocket", "atomy"], user="king@x")
|
||||
assert res == [] and not st.events and not st.status
|
||||
for code in ("coupang_rocket", "atomy"):
|
||||
assert display_status({"code": code, "enabled": True}, None, False) == "manual"
|
||||
assert display_status({"code": "coupang_rocket", "enabled": False}, None, False) == "disabled"
|
||||
assert display_status({"code": "ohouse", "enabled": True}, None, False) == "not_configured"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||
n = 0
|
||||
@@ -1729,3 +2055,112 @@ if __name__ == "__main__":
|
||||
n += 1
|
||||
print("ok", name)
|
||||
print(f"{n} tests passed")
|
||||
|
||||
|
||||
def test_manual_sale_api_rules():
|
||||
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503.
|
||||
켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
import importlib
|
||||
|
||||
from app.modules.performance import common
|
||||
from app.modules.performance.db import ManualMigrationNeeded
|
||||
|
||||
router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
|
||||
|
||||
class St:
|
||||
def __init__(self):
|
||||
self.saved, self.updated, self.missing = [], [], False
|
||||
|
||||
def list_marketplaces(self):
|
||||
return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}]
|
||||
|
||||
def set_manual_sale(self, code, day, amount, *, user=""):
|
||||
if self.missing:
|
||||
raise ManualMigrationNeeded()
|
||||
self.saved.append((code, day, amount, user))
|
||||
|
||||
def api_amount(self, code, day):
|
||||
return 50000
|
||||
|
||||
def update_marketplace(self, code, **kw):
|
||||
if self.missing and kw.get("manual_input") is not None:
|
||||
raise ManualMigrationNeeded()
|
||||
self.updated.append((code, kw))
|
||||
return {"code": code}
|
||||
|
||||
st = St()
|
||||
seen = {}
|
||||
|
||||
def fake_require(request, *, admin=False):
|
||||
seen["admin"] = admin
|
||||
return st, {"email": "me@test.local"}
|
||||
|
||||
def status_of(fn):
|
||||
try:
|
||||
fn()
|
||||
except HTTPException as exc:
|
||||
return exc.status_code, exc.detail
|
||||
return 200, ""
|
||||
|
||||
orig = (common.require_store, router.today_kst)
|
||||
common.require_store, router.today_kst = fake_require, (lambda: date(2026, 10, 12))
|
||||
try:
|
||||
r = router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "87,000"})
|
||||
body = __import__("json").loads(r.body)
|
||||
assert st.saved[-1] == ("coupang", date(2026, 10, 12), 87000, "me@test.local") and seen["admin"] is False
|
||||
assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000
|
||||
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body)
|
||||
assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값
|
||||
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날
|
||||
code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1}))
|
||||
assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰
|
||||
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400
|
||||
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 10 ** 13}))[0] == 400
|
||||
assert status_of(lambda: router.api_manual_sale(None, "nope", "2026-10-12", {"amount": 1}))[0] == 404
|
||||
router.api_update_marketplace(None, "coupang", {"manual_input": True})
|
||||
assert seen["admin"] is True and st.updated[-1] == ("coupang", {"enabled": None, "include_in_sales": None, "manual_input": True})
|
||||
st.missing = True
|
||||
code, msg = status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 1}))
|
||||
assert code == 503 and "002" in msg
|
||||
assert status_of(lambda: router.api_update_marketplace(None, "coupang", {"manual_input": False}))[0] == 503
|
||||
finally:
|
||||
common.require_store, router.today_kst = orig
|
||||
|
||||
|
||||
def test_dashboard_manual_cells_and_order():
|
||||
"""대시보드 — 수동 입력 켠 쇼핑몰만 manual_codes, 값이 있는 칸만 manual_cells, 수동 값이 그날 금액(수수료도 그 값으로)."""
|
||||
from decimal import Decimal
|
||||
|
||||
from app.modules.performance.dashboard import build_dashboard
|
||||
|
||||
class St:
|
||||
def list_marketplaces(self):
|
||||
return [{"code": c, "name": c, "enabled": True, "include_in_sales": True, "manual_input": c == "coupang"}
|
||||
for c in ("cafe24", "naver", "coupang", "toss")]
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
return {(date(2026, 10, 5), "coupang"): 87000} # 저장소가 이미 수동 값으로 바꿔 돌려준다
|
||||
|
||||
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||
assert codes == ["coupang"]
|
||||
return {(date(2026, 10, 5), "coupang"): 87000} if start <= date(2026, 10, 5) <= end else {}
|
||||
|
||||
def rate_table(self):
|
||||
return {"coupang": [(date(2026, 1, 1), Decimal("10"))]}
|
||||
|
||||
def statuses(self):
|
||||
return {}
|
||||
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
ctx = build_dashboard(St(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
assert ctx["codes"] == ["cafe24", "naver", "coupang", "toss"]
|
||||
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700
|
||||
|
||||
Binary file not shown.
+463
-20
@@ -49,6 +49,11 @@ class ProjectStore:
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
@property
|
||||
def pool(self) -> Any:
|
||||
"""같은 project_db 를 쓰는 다른 저장소(긴급 공지 — app/modules/notice)가 연결 풀을 같이 쓴다."""
|
||||
return self._pool
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 프로젝트 / 서브프로젝트
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -693,12 +698,12 @@ class ProjectStore:
|
||||
"SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,)
|
||||
).fetchone()
|
||||
if not parent:
|
||||
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
|
||||
raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}")
|
||||
# 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트
|
||||
# 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는
|
||||
# 프로젝트에 세부 업무를 만들 수 있었다).
|
||||
if int(parent["project_id"]) != int(project_id):
|
||||
raise ValueError("상위 작업이 이 프로젝트에 속하지 않습니다.")
|
||||
raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.")
|
||||
stage_id = None
|
||||
elif stage_id not in (None, ""):
|
||||
stage_id = self._check_stage_in_project(conn, stage_id, project_id)
|
||||
@@ -771,19 +776,19 @@ class ProjectStore:
|
||||
(task_id,),
|
||||
).fetchone()
|
||||
if not sub:
|
||||
raise KeyError(f"작업을 찾을 수 없습니다: {task_id}")
|
||||
raise KeyError(f"업무를 찾을 수 없습니다: {task_id}")
|
||||
if sub["parent_task_id"] is None:
|
||||
raise ValueError("세부 작업만 다른 작업으로 옮길 수 있습니다.")
|
||||
raise ValueError("세부 업무만 다른 업무로 옮길 수 있습니다.")
|
||||
parent = conn.execute(
|
||||
"SELECT id, project_id, parent_task_id, title FROM tasks WHERE id = %s",
|
||||
(parent_task_id,),
|
||||
).fetchone()
|
||||
if not parent:
|
||||
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
|
||||
raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}")
|
||||
if parent["parent_task_id"] is not None:
|
||||
raise ValueError("세부 작업 안으로는 옮길 수 없습니다.")
|
||||
raise ValueError("세부 업무 안으로는 옮길 수 없습니다.")
|
||||
if int(parent["project_id"]) != int(sub["project_id"]):
|
||||
raise ValueError("다른 프로젝트의 작업으로는 옮길 수 없습니다.")
|
||||
raise ValueError("다른 프로젝트의 업무로는 옮길 수 없습니다.")
|
||||
if int(parent["id"]) != int(sub["parent_task_id"]):
|
||||
nxt = conn.execute(
|
||||
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
||||
@@ -913,6 +918,8 @@ class ProjectStore:
|
||||
store.validate_date_range(final("start_date"), final("due_date"),
|
||||
final("start_time"), final("due_time"))
|
||||
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
||||
if "assignee_email" in assignee_fields:
|
||||
self._drop_assignee_follower(conn, task_id, assignee_fields["assignee_email"])
|
||||
if newly_assigned:
|
||||
self._log(conn, project_id=prev["project_id"], task_id=task_id,
|
||||
actor=actor, action=store.ACTION_ASSIGNED,
|
||||
@@ -928,6 +935,88 @@ class ProjectStore:
|
||||
out["_newly_completed"] = newly_completed if changed else False
|
||||
return out
|
||||
|
||||
def move_task_to_project(
|
||||
self, *, task_id: int, project_id: int, stage_id: Any = None, actor: str = "",
|
||||
assignee_allowed: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""메인 업무를 다른 프로젝트(의 섹션)로 옮긴다 — 세부 업무(모든 단계)도 함께. 한 트랜잭션.
|
||||
|
||||
· 메인 업무만(세부 업무는 상위 업무와 함께 움직인다). 같은 프로젝트면 ValueError.
|
||||
· 섹션은 대상 프로젝트 것만(None = 섹션 없음). 목록 끝(sort_order 최대+1)으로.
|
||||
· 섹션을 옮길 때와 같은 규칙 — 담당자가 비었으면 그 섹션 기본 담당자, 완료 섹션이면 완료 처리.
|
||||
· 대상 프로젝트로 걸려 있던 연결(멀티호밍)은 이제 원 소속이라 지운다(다른 연결은 그대로).
|
||||
· 활동 이력·알림·회의록 업무 등록 줄의 프로젝트도 따라 바꾼다(이력이 새 프로젝트 화면에 보이게).
|
||||
반환: 옮긴 업무(get_task) + `_moved_ids`·`_newly_assigned`·`_newly_completed`.
|
||||
"""
|
||||
newly_assigned: str | None = None
|
||||
newly_completed = False
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute("SELECT * FROM tasks WHERE id = %s FOR UPDATE", (task_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(f"업무를 찾을 수 없습니다: {task_id}")
|
||||
prev = self._serialize(row)
|
||||
if prev.get("parent_task_id") is not None:
|
||||
raise ValueError("세부 업무는 상위 업무와 함께 옮겨집니다. 상위 업무를 옮기세요.")
|
||||
target = int(project_id)
|
||||
if int(prev["project_id"]) == target:
|
||||
raise ValueError("이미 이 프로젝트의 업무입니다.")
|
||||
if not conn.execute("SELECT 1 FROM projects WHERE id = %s", (target,)).fetchone():
|
||||
raise KeyError(f"프로젝트를 찾을 수 없습니다: {target}")
|
||||
new_stage = self._check_stage_in_project(conn, stage_id, target)
|
||||
ids = [int(r["id"]) for r in conn.execute(
|
||||
"WITH RECURSIVE tree AS (SELECT id FROM tasks WHERE id = %s "
|
||||
"UNION ALL SELECT t.id FROM tasks t JOIN tree ON t.parent_task_id = tree.id) "
|
||||
"SELECT id FROM tree",
|
||||
(task_id,),
|
||||
).fetchall()]
|
||||
nxt = conn.execute(
|
||||
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks WHERE project_id = %s",
|
||||
(target,),
|
||||
).fetchone()
|
||||
conn.execute("UPDATE tasks SET project_id = %s WHERE id = ANY(%s)", (target, ids))
|
||||
sets = ["stage_id = %s", "sort_order = %s"]
|
||||
params: list[Any] = [new_stage, int(nxt["n"])]
|
||||
if new_stage is not None and not (prev.get("assignee_email") or ""):
|
||||
dae, dan = self._stage_default_assignee(conn, new_stage, target, allowed=assignee_allowed)
|
||||
if dae:
|
||||
sets += ["assignee_email = %s", "assignee_name = %s"]
|
||||
params += [dae, dan]
|
||||
newly_assigned = dae
|
||||
if self._stage_is_done_conn(conn, new_stage) and not prev.get("completed_at"):
|
||||
sets.append("completed_at = %s")
|
||||
params.append(now_kst())
|
||||
newly_completed = True
|
||||
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
||||
if newly_assigned:
|
||||
self._drop_assignee_follower(conn, task_id, newly_assigned)
|
||||
conn.execute(
|
||||
"DELETE FROM task_project_links WHERE task_id = ANY(%s) AND project_id = %s", (ids, target))
|
||||
conn.execute("UPDATE project_activity SET project_id = %s WHERE task_id = ANY(%s)", (target, ids))
|
||||
conn.execute("UPDATE project_notifications SET project_id = %s WHERE task_id = ANY(%s)", (target, ids))
|
||||
if self._table_exists(conn, "goal_meeting_tasks"):
|
||||
conn.execute(
|
||||
"UPDATE goal_meeting_tasks SET project_id = %s, stage_id = %s WHERE task_id = %s",
|
||||
(target, new_stage, task_id))
|
||||
old_name = conn.execute("SELECT name FROM projects WHERE id = %s", (prev["project_id"],)).fetchone()
|
||||
new_name = conn.execute("SELECT name FROM projects WHERE id = %s", (target,)).fetchone()
|
||||
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||
action=store.ACTION_PROJECT_MOVED,
|
||||
detail=f"{prev['title']}: {(old_name or {}).get('name', '')} → {(new_name or {}).get('name', '')}")
|
||||
if newly_assigned:
|
||||
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||
action=store.ACTION_ASSIGNED, detail=f"{prev['title']} → {newly_assigned}")
|
||||
if newly_completed:
|
||||
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||
action=store.ACTION_COMPLETED, detail=prev["title"])
|
||||
out = self.get_task(task_id=task_id)
|
||||
if out is None:
|
||||
raise KeyError(task_id)
|
||||
out["_moved_ids"] = ids
|
||||
out["_newly_assigned"] = newly_assigned
|
||||
out["_newly_completed"] = newly_completed
|
||||
return out
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -1068,23 +1157,23 @@ class ProjectStore:
|
||||
payload = tr["payload"] or {}
|
||||
tasks = list(payload.get("tasks") or [])
|
||||
if not tasks:
|
||||
raise ValueError("복구할 작업 데이터가 없습니다.")
|
||||
raise ValueError("복구할 업무 데이터가 없습니다.")
|
||||
ids = [int(t["id"]) for t in tasks]
|
||||
clash = conn.execute(
|
||||
"SELECT id FROM tasks WHERE id = ANY(%s) LIMIT 1", (ids,)
|
||||
).fetchone()
|
||||
if clash:
|
||||
raise ValueError(f"이미 같은 작업(id {clash['id']})이 있어 복구할 수 없습니다.")
|
||||
raise ValueError(f"이미 같은 업무(id {clash['id']})이 있어 복구할 수 없습니다.")
|
||||
project_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM projects").fetchall()}
|
||||
stage_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM project_stages").fetchall()}
|
||||
root = next((t for t in tasks if int(t["id"]) == int(tr["task_id"])), tasks[0])
|
||||
if int(root["project_id"]) not in project_ids:
|
||||
raise ValueError("작업이 속했던 프로젝트가 삭제되어 복구할 수 없습니다.")
|
||||
raise ValueError("업무가 속했던 프로젝트가 삭제되어 복구할 수 없습니다.")
|
||||
parent = root.get("parent_task_id")
|
||||
if parent and int(parent) not in ids:
|
||||
ok = conn.execute("SELECT 1 FROM tasks WHERE id = %s", (int(parent),)).fetchone()
|
||||
if not ok:
|
||||
raise ValueError("상위 작업이 없어 복구할 수 없습니다 — 상위 작업을 먼저 복구하세요.")
|
||||
raise ValueError("상위 업무가 없어 복구할 수 없습니다 — 상위 업무를 먼저 복구하세요.")
|
||||
for t in tasks:
|
||||
if t.get("stage_id") is not None and int(t["stage_id"]) not in stage_ids:
|
||||
t["stage_id"] = None
|
||||
@@ -1830,6 +1919,21 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def list_my_overdue(self, *, assignee_email: str, today: Any, limit: int = 200) -> list[dict[str, Any]]:
|
||||
"""내가 담당인 미완료 업무 중 마감일이 오늘 이전인 것(세부 업무 포함, 마감 오래된 것부터)."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT t.id, t.title, t.due_date, t.project_id, t.parent_task_id, "
|
||||
" p.name AS project_name, p.color AS project_color, pt.title AS parent_title "
|
||||
"FROM tasks t JOIN projects p ON p.id = t.project_id "
|
||||
"LEFT JOIN tasks pt ON pt.id = t.parent_task_id "
|
||||
"WHERE t.assignee_email = %s AND t.completed_at IS NULL "
|
||||
" AND t.due_date IS NOT NULL AND t.due_date < %s "
|
||||
"ORDER BY t.due_date ASC, t.id ASC LIMIT %s",
|
||||
(store.norm_str(assignee_email, lower=True), today, int(limit)),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]:
|
||||
"""내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다."""
|
||||
with self._pool.connection() as conn:
|
||||
@@ -1876,8 +1980,25 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
return [r["user_email"] for r in rows]
|
||||
|
||||
def list_followers_of(self, *, task_ids: list[int]) -> dict[int, list[str]]:
|
||||
"""여러 업무의 협업자를 한 번에 — 업무 창 세부 업무 줄의 협업자 아이콘용."""
|
||||
ids = [int(i) for i in task_ids]
|
||||
if not ids:
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT task_id, user_email FROM task_followers WHERE task_id = ANY(%s) "
|
||||
"ORDER BY created_at ASC, user_email ASC",
|
||||
(ids,),
|
||||
).fetchall()
|
||||
out: dict[int, list[str]] = {i: [] for i in ids}
|
||||
for r in rows:
|
||||
out[int(r["task_id"])].append(r["user_email"])
|
||||
return out
|
||||
|
||||
def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]:
|
||||
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다."""
|
||||
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다.
|
||||
그 업무의 담당자는 넣지 않는다 — 협업자는 담당자 외의 멤버(2026-10-13)."""
|
||||
targets = store.normalize_emails(emails)
|
||||
if not targets:
|
||||
return []
|
||||
@@ -1885,11 +2006,18 @@ class ProjectStore:
|
||||
rows = conn.execute(
|
||||
"INSERT INTO task_followers (task_id, user_email) "
|
||||
"SELECT %s, e FROM unnest(%s::text[]) AS e "
|
||||
"WHERE e <> COALESCE((SELECT lower(assignee_email) FROM tasks WHERE id = %s), '') "
|
||||
"ON CONFLICT DO NOTHING RETURNING user_email",
|
||||
(task_id, targets),
|
||||
(task_id, targets, task_id),
|
||||
).fetchall()
|
||||
return [r["user_email"] for r in rows]
|
||||
|
||||
def _drop_assignee_follower(self, conn: Any, task_id: int, email: str) -> None:
|
||||
"""새 담당자는 협업자에서 뺀다(같은 트랜잭션). 008 미적용이면 건너뜀."""
|
||||
if email and self._table_exists(conn, "task_followers"):
|
||||
conn.execute("DELETE FROM task_followers WHERE task_id = %s AND user_email = %s",
|
||||
(task_id, store.norm_str(email, lower=True)))
|
||||
|
||||
def remove_follower(self, *, task_id: int, user_email: str) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
@@ -2771,7 +2899,23 @@ class ProjectStore:
|
||||
return (self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "")
|
||||
+ (", content_row_span" if self._meeting_cells(conn) else "")
|
||||
+ (", result_note" if self._meeting_v20(conn) else "")
|
||||
+ (", target_text, result_text" if self._meeting_v21(conn) else ""))
|
||||
+ (", target_text, result_text" if self._meeting_v21(conn) else "")
|
||||
+ (", label_cont" if self._meeting_v27(conn) else ""))
|
||||
|
||||
def _meeting_v27(self, conn: Any) -> bool:
|
||||
"""마이그레이션 027 — 항목 칸 묶음(label_cont: 바로 위 줄의 항목 칸에 이어 붙는 줄)."""
|
||||
if getattr(self, "_meeting_v27_ok", False):
|
||||
return True
|
||||
ok = self._column_exists(conn, "goal_meeting_items", "label_cont")
|
||||
if ok:
|
||||
self._meeting_v27_ok = True
|
||||
return ok
|
||||
|
||||
@staticmethod
|
||||
def _meeting_conts(rows: list[dict[str, Any]]) -> list[bool]:
|
||||
"""줄 순서대로 '실제로 이어 붙은 줄'인가 — label_cont 이고 바로 위 줄이 같은 구역일 때만(구역 첫 줄은 늘 묶음 첫 줄)."""
|
||||
return [bool(r.get("label_cont")) and i > 0 and rows[i - 1]["section"] == r["section"]
|
||||
for i, r in enumerate(rows)]
|
||||
|
||||
def _meeting_v21(self, conn: Any) -> bool:
|
||||
"""마이그레이션 021 — 정량 목표·결과 글(target_text·result_text, 예: "20개")."""
|
||||
@@ -2994,6 +3138,7 @@ class ProjectStore:
|
||||
if ws.weekday() != 0 and not self._meeting_v20(conn):
|
||||
raise store.MeetingMigration020Needed() # 월요일만 허용하던 CHECK 가 아직 있다
|
||||
keyed = self._meeting_keys(conn)
|
||||
v27 = self._meeting_v27(conn)
|
||||
ins = conn.execute(
|
||||
"INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) "
|
||||
"ON CONFLICT (week_start) DO NOTHING RETURNING week_start",
|
||||
@@ -3001,7 +3146,8 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
if ins is None:
|
||||
return False
|
||||
src_cols = "id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
||||
src_cols = ("id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
||||
+ (", label_cont" if v27 else ""))
|
||||
src_items: list[dict[str, Any]] = []
|
||||
src_is_prev = True
|
||||
for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)):
|
||||
@@ -3037,6 +3183,12 @@ class ProjectStore:
|
||||
"marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who),
|
||||
)
|
||||
if v27 and r.get("label_cont"):
|
||||
# 항목 칸 묶음도 그대로 이어받는다(027) — 방금 넣은 줄(같은 주차·순서)
|
||||
conn.execute(
|
||||
"UPDATE goal_meeting_items SET label_cont = true WHERE week_start = %s AND sort_order = %s",
|
||||
(ws, n),
|
||||
)
|
||||
else:
|
||||
n = 0
|
||||
for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]:
|
||||
@@ -3103,9 +3255,14 @@ class ProjectStore:
|
||||
|
||||
def add_meeting_item(
|
||||
self, *, week_start: date, section: str, section_color: str = "", label: str = "",
|
||||
ref_item_id: int | None = None, place: str = "below", updated_by: str = "",
|
||||
ref_item_id: int | None = None, place: str = "below", updated_by: str = "", same_label: bool = False,
|
||||
) -> int:
|
||||
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역)."""
|
||||
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역).
|
||||
|
||||
same_label(주요 업무 칸에서 추가, 027) = 새 줄을 기준 줄과 **같은 항목 칸** 안에: 아래면 새 줄이 이어 붙고(label_cont),
|
||||
위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다(연간 목표 016 과 같은 규칙)."""
|
||||
if same_label and ref_item_id is None:
|
||||
raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.")
|
||||
sec = store.norm_str(section)
|
||||
if not sec or len(sec) > store.MEETING_LABEL_MAX:
|
||||
raise ValueError("구역 이름을 입력하세요(50자 이하).")
|
||||
@@ -3136,14 +3293,31 @@ class ProjectStore:
|
||||
i = same[-1] + 1 if same else len(ids)
|
||||
if any(a < i <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||
raise ValueError("병합된 셀 안에 줄을 추가하려면 먼저 병합을 해제해 주세요.")
|
||||
cont = False
|
||||
if same_label:
|
||||
if not self._meeting_v27(conn):
|
||||
raise store.MeetingMigration027Needed()
|
||||
k = ids.index(ref_item_id)
|
||||
ref = rows[k]
|
||||
if ref["section"] != sec:
|
||||
raise ValueError("기준 줄과 같은 구역이어야 합니다.")
|
||||
if place == "above" and not self._meeting_conts(rows)[k]:
|
||||
# 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다
|
||||
lb = ref["label"]
|
||||
conn.execute("UPDATE goal_meeting_items SET label = '', label_cont = true WHERE id = %s",
|
||||
(ref_item_id,))
|
||||
else:
|
||||
lb, cont = "", True
|
||||
# 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다
|
||||
keyed = self._meeting_keys(conn)
|
||||
v27 = self._meeting_v27(conn)
|
||||
new_id = int(conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
|
||||
"sort_order, updated_by" + (", line_key" if keyed else "") + ") VALUES (%s,%s,%s,%s,%s,0,%s"
|
||||
+ (",%s" if keyed else "") + ") RETURNING id",
|
||||
"sort_order, updated_by" + (", line_key" if keyed else "") + (", label_cont" if v27 else "")
|
||||
+ ") VALUES (%s,%s,%s,%s,%s,0,%s" + (",%s" if keyed else "") + (",%s" if v27 else "") + ") RETURNING id",
|
||||
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
|
||||
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ())),
|
||||
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ()),
|
||||
*((cont,) if v27 else ())),
|
||||
).fetchone()["id"])
|
||||
ids.insert(i, new_id)
|
||||
for n, x in enumerate(ids):
|
||||
@@ -3299,6 +3473,15 @@ class ProjectStore:
|
||||
i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id)
|
||||
if any(a <= i <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||
raise ValueError("병합된 셀의 줄을 삭제하려면 먼저 병합을 해제해 주세요.")
|
||||
if self._meeting_v27(conn):
|
||||
# 항목 칸 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면)
|
||||
conts = self._meeting_conts(rows)
|
||||
if not conts[i] and i + 1 < len(rows) and conts[i + 1]:
|
||||
conn.execute(
|
||||
"UPDATE goal_meeting_items SET label_cont = false, "
|
||||
"label = CASE WHEN label = '' THEN %s ELSE label END WHERE id = %s",
|
||||
(rows[i]["label"], rows[i + 1]["id"]),
|
||||
)
|
||||
row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(item_id)
|
||||
@@ -3316,10 +3499,270 @@ class ProjectStore:
|
||||
return
|
||||
if any(a <= i <= b or a <= j <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||
raise ValueError("병합된 셀의 줄을 이동하려면 먼저 병합을 해제해 주세요.")
|
||||
conts = self._meeting_conts(rows)
|
||||
in_group = lambda k: conts[k] or (k + 1 < len(rows) and conts[k + 1]) # noqa: E731
|
||||
if in_group(i) or in_group(j):
|
||||
raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.")
|
||||
ids[i], ids[j] = ids[j], ids[i]
|
||||
for n, x in enumerate(ids):
|
||||
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||
|
||||
def move_meeting_section(self, *, item_id: int, direction: int) -> None:
|
||||
"""구역(표 첫 열 "구분") 통째로 한 칸 위/아래 — item_id 가 든 구역 묶음(이어진 같은 구역 줄)과 옆 구역 묶음의
|
||||
자리를 바꾼다. 묶음 안 줄 순서·세로 병합(content_row_span)은 그대로 따라간다. 맨 위/맨 아래면 그대로."""
|
||||
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]
|
||||
blocks: list[list[int]] = [] # 이어진 같은 구역 줄 묶음(화면의 tbody 하나)
|
||||
for i, r in enumerate(rows):
|
||||
if i and r["section"] == rows[i - 1]["section"]:
|
||||
blocks[-1].append(ids[i])
|
||||
else:
|
||||
blocks.append([ids[i]])
|
||||
b = next(n for n, blk in enumerate(blocks) if item_id in blk)
|
||||
j = b + (1 if direction > 0 else -1)
|
||||
if not 0 <= j < len(blocks):
|
||||
return
|
||||
blocks[b], blocks[j] = blocks[j], blocks[b]
|
||||
order = [x for blk in blocks for x in blk]
|
||||
for n, x in enumerate(order):
|
||||
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||
|
||||
def split_meeting_label(self, *, item_id: int) -> int:
|
||||
"""항목 칸 나누기(027) — item_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수."""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
self._require_meetings(conn)
|
||||
if not self._meeting_v27(conn):
|
||||
raise store.MeetingMigration027Needed()
|
||||
rows = self._locked_meeting_items(conn, item_id)
|
||||
conts = self._meeting_conts(rows)
|
||||
i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id)
|
||||
n = 0
|
||||
for k in range(i + 1, len(rows)):
|
||||
if not conts[k]:
|
||||
break
|
||||
conn.execute("UPDATE goal_meeting_items SET label_cont = false WHERE id = %s", (rows[k]["id"],))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
# ── 회의록 작업 등록 표(025) — 주차별 한 표, 모두가 같이 본다. [적용] 전 줄은 고치고, [적용]은 한 번만 ──
|
||||
# 026 — 작업 칸(parent_task_id): 고르면 [적용] 때 그 작업의 세부 작업으로(비우면 그 섹션에 새 작업).
|
||||
# 025 의 parent_id(표 안 줄끼리 세부 작업)는 화면에서 쓰지 않는다(열·값은 그대로, 읽기·쓰기 안 함).
|
||||
_MT_BASE = ("id, week_start, sort_order, title, assignee_email, project_id, stage_id, task_id, "
|
||||
"created_by, updated_by, created_at, updated_at")
|
||||
|
||||
def _mt_v26(self, conn: Any) -> bool:
|
||||
"""026(작업 칸 parent_task_id) 적용 여부 — 적용되면 한 번만 확인."""
|
||||
if getattr(self, "_mt_v26_ok", False):
|
||||
return True
|
||||
ok = self._column_exists(conn, "goal_meeting_tasks", "parent_task_id")
|
||||
if ok:
|
||||
self._mt_v26_ok = True
|
||||
return ok
|
||||
|
||||
def _mt_cols(self, conn: Any, prefix: str = "") -> str:
|
||||
cols = [prefix + c.strip() for c in self._MT_BASE.split(",")]
|
||||
if self._mt_v26(conn):
|
||||
cols.append(prefix + "parent_task_id")
|
||||
return ", ".join(cols)
|
||||
|
||||
def _mt_conn(self) -> Any:
|
||||
return self._pool.connection()
|
||||
|
||||
@staticmethod
|
||||
def _mt_call(fn: Any) -> Any:
|
||||
try:
|
||||
return fn()
|
||||
except psycopg_errors.UndefinedTable:
|
||||
raise store.MeetingTaskMigrationNeeded()
|
||||
|
||||
@staticmethod
|
||||
def _mt_row(r: dict[str, Any]) -> dict[str, Any]:
|
||||
out = {k: r.get(k) for k in ("id", "sort_order", "title", "assignee_email", "project_id",
|
||||
"stage_id", "task_id", "parent_task_id", "created_by", "updated_by")}
|
||||
for k in ("id", "project_id", "stage_id", "task_id", "parent_task_id"):
|
||||
out[k] = int(out[k]) if out[k] is not None else None
|
||||
out["week_start"] = r["week_start"].isoformat()
|
||||
out["updated_at"] = r["updated_at"].astimezone(KST).isoformat(timespec="seconds") if r.get("updated_at") else ""
|
||||
for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title"):
|
||||
if k in r:
|
||||
out[k] = r[k]
|
||||
if "task_exists" in r:
|
||||
out["task_exists"] = bool(r["task_exists"])
|
||||
return out
|
||||
|
||||
def _mt_clean(self, conn: Any, fields: dict[str, Any], *, project_id: Any = None) -> dict[str, Any]:
|
||||
"""고칠 칸 정리 — title(200자)·assignee_email·project_id·stage_id(그 프로젝트 섹션)·parent_task_id(그 프로젝트 작업, 026).
|
||||
프로젝트가 바뀌면 섹션·작업을 비운다."""
|
||||
clean: dict[str, Any] = {}
|
||||
v26 = self._mt_v26(conn)
|
||||
if "title" in fields:
|
||||
t = store.norm_str(fields.get("title"))
|
||||
if len(t) > 200:
|
||||
raise ValueError("업무 제목은 200자 이하로 입력하세요.")
|
||||
clean["title"] = t
|
||||
if "assignee_email" in fields:
|
||||
clean["assignee_email"] = store.norm_str(fields.get("assignee_email") or "", lower=True)
|
||||
pid = project_id
|
||||
if "project_id" in fields:
|
||||
raw = fields.get("project_id")
|
||||
try:
|
||||
pid = int(raw) if raw not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("프로젝트 값이 올바르지 않습니다.")
|
||||
clean["project_id"] = pid
|
||||
if "stage_id" not in fields:
|
||||
clean["stage_id"] = None
|
||||
if v26 and "parent_task_id" not in fields:
|
||||
clean["parent_task_id"] = None
|
||||
if "stage_id" in fields:
|
||||
sid = fields.get("stage_id")
|
||||
if sid in (None, ""):
|
||||
clean["stage_id"] = None
|
||||
else:
|
||||
if pid is None:
|
||||
raise ValueError("프로젝트를 먼저 고르세요.")
|
||||
clean["stage_id"] = self._check_stage_in_project(conn, sid, int(pid))
|
||||
if "parent_task_id" in fields:
|
||||
if not v26:
|
||||
raise store.MeetingParentTaskMigrationNeeded()
|
||||
raw = fields.get("parent_task_id")
|
||||
if raw in (None, ""):
|
||||
clean["parent_task_id"] = None
|
||||
else:
|
||||
try:
|
||||
tid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("업무 값이 올바르지 않습니다.")
|
||||
if pid is None:
|
||||
raise ValueError("프로젝트를 먼저 고르세요.")
|
||||
t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (tid,)).fetchone()
|
||||
if t is None or int(t["project_id"]) != int(pid):
|
||||
raise ValueError("이 프로젝트의 업무가 아닙니다.")
|
||||
clean["parent_task_id"] = tid
|
||||
return clean
|
||||
|
||||
def _mt_select(self, conn: Any, where: str, params: tuple[Any, ...]) -> list[dict[str, Any]]:
|
||||
"""줄 + 프로젝트·섹션·고른 작업 이름 + 만든 작업 존재 여부(목록·한 줄 응답 공용)."""
|
||||
v26 = self._mt_v26(conn)
|
||||
return conn.execute(
|
||||
f"SELECT {self._mt_cols(conn, 'm.')}, "
|
||||
" p.name AS project_name, p.status AS project_status, s.name AS stage_name, "
|
||||
" t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists"
|
||||
+ (", pt.title AS parent_task_title " if v26 else " ") +
|
||||
"FROM goal_meeting_tasks m "
|
||||
"LEFT JOIN projects p ON p.id = m.project_id "
|
||||
"LEFT JOIN project_stages s ON s.id = m.stage_id "
|
||||
"LEFT JOIN tasks t ON t.id = m.task_id "
|
||||
+ ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " if v26 else "") +
|
||||
f"WHERE {where} ORDER BY m.sort_order, m.id", params,
|
||||
).fetchall()
|
||||
|
||||
def list_meeting_tasks(self, *, week_start: date) -> list[dict[str, Any]]:
|
||||
"""그 주차 표 — 순서대로. 프로젝트·섹션·고른 작업 이름, 만든 작업 존재 여부를 붙인다."""
|
||||
def run() -> list[dict[str, Any]]:
|
||||
with self._mt_conn() as conn:
|
||||
return [self._mt_row(r) for r in self._mt_select(conn, "m.week_start = %s", (week_start,))]
|
||||
return self._mt_call(run)
|
||||
|
||||
def get_meeting_task(self, *, item_id: int) -> dict[str, Any] | None:
|
||||
def run() -> dict[str, Any] | None:
|
||||
with self._mt_conn() as conn:
|
||||
rows = self._mt_select(conn, "m.id = %s", (item_id,))
|
||||
return self._mt_row(rows[0]) if rows else None
|
||||
return self._mt_call(run)
|
||||
|
||||
def add_meeting_task(self, *, week_start: date, fields: dict[str, Any], by: str = "",
|
||||
task_id: int | None = None) -> dict[str, Any]:
|
||||
"""줄 추가(빈 줄도). task_id = 예전 브라우저 표에서 옮겨 온 이미 등록된 줄."""
|
||||
who = store.norm_str(by, lower=True)
|
||||
|
||||
def run() -> int:
|
||||
with self._mt_conn() as conn:
|
||||
with conn.transaction():
|
||||
self._check_meeting_open(conn, week_start)
|
||||
clean = self._mt_clean(conn, fields)
|
||||
nxt = conn.execute("SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM goal_meeting_tasks "
|
||||
"WHERE week_start = %s", (week_start,)).fetchone()["n"]
|
||||
cols = ["week_start", "sort_order", "title", "assignee_email", "project_id", "stage_id", "task_id",
|
||||
"created_by", "updated_by"]
|
||||
vals = [week_start, int(nxt), clean.get("title", ""), clean.get("assignee_email", ""),
|
||||
clean.get("project_id"), clean.get("stage_id"), task_id, who, who]
|
||||
if clean.get("parent_task_id") is not None:
|
||||
cols.append("parent_task_id")
|
||||
vals.append(clean["parent_task_id"])
|
||||
return int(conn.execute(
|
||||
f"INSERT INTO goal_meeting_tasks ({', '.join(cols)}) VALUES ({', '.join(['%s'] * len(cols))}) "
|
||||
"RETURNING id", vals,
|
||||
).fetchone()["id"])
|
||||
return self.get_meeting_task(item_id=self._mt_call(run)) # type: ignore[return-value]
|
||||
|
||||
def update_meeting_task(self, *, item_id: int, fields: dict[str, Any], by: str = "") -> dict[str, Any]:
|
||||
"""[적용] 전 줄만 고친다(줄을 잠그고 — 다른 사람이 막 [적용]한 줄은 409). 회의 완료된 주차면 잠금."""
|
||||
def run() -> None:
|
||||
with self._mt_conn() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute("SELECT week_start, project_id, task_id FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||
(item_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(item_id)
|
||||
self._check_meeting_open(conn, row["week_start"])
|
||||
if row["task_id"] is not None:
|
||||
raise store.GoalCellConflict("이미 [적용]해 업무로 만든 줄입니다. 새로고침해 주세요.")
|
||||
clean = self._mt_clean(conn, fields, project_id=row["project_id"])
|
||||
if not clean:
|
||||
return
|
||||
sets = ", ".join(f"{k} = %s" for k in clean)
|
||||
conn.execute(f"UPDATE goal_meeting_tasks SET {sets}, updated_by = %s, updated_at = now() WHERE id = %s",
|
||||
(*clean.values(), store.norm_str(by, lower=True), item_id))
|
||||
self._mt_call(run)
|
||||
return self.get_meeting_task(item_id=item_id) # type: ignore[return-value]
|
||||
|
||||
def delete_meeting_task(self, *, item_id: int) -> dict[str, Any]:
|
||||
"""줄 지우기. 만든 작업은 라우터·화면이 따로 지운다(휴지통)."""
|
||||
def run() -> dict[str, Any]:
|
||||
with self._mt_conn() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||
(item_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(item_id)
|
||||
self._check_meeting_open(conn, row["week_start"])
|
||||
conn.execute("DELETE FROM goal_meeting_tasks WHERE id = %s", (item_id,))
|
||||
return self._mt_row(row)
|
||||
return self._mt_call(run)
|
||||
|
||||
def apply_meeting_task(self, *, item_id: int, create: Any) -> tuple[dict[str, Any], bool]:
|
||||
"""[적용] — 줄을 잠그고 아직 작업이 없을 때만 create(줄, 상위 작업 id) 로 작업을 만들어 task_id 를 남긴다.
|
||||
작업 칸(parent_task_id)을 골랐으면 그 작업의 세부 작업으로(섹션 없이). (줄, 이번에 만들었는가).
|
||||
두 사람이 동시에 눌러도 작업은 하나. create 가 실패하면 줄은 그대로."""
|
||||
def run() -> tuple[int, bool]:
|
||||
with self._mt_conn() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||
(item_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(item_id)
|
||||
self._check_meeting_open(conn, row["week_start"])
|
||||
if row["task_id"] is not None:
|
||||
return item_id, False
|
||||
use = self._mt_row(row)
|
||||
parent_task = use.get("parent_task_id")
|
||||
if parent_task is not None:
|
||||
t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (parent_task,)).fetchone()
|
||||
if t is None or use["project_id"] is None or int(t["project_id"]) != int(use["project_id"]):
|
||||
raise ValueError("고른 업무가 없어졌거나 다른 프로젝트로 옮겨졌습니다. 업무 칸을 다시 고르세요.")
|
||||
use = {**use, "stage_id": None}
|
||||
task = create(use, parent_task)
|
||||
conn.execute("UPDATE goal_meeting_tasks SET task_id = %s, updated_at = now() WHERE id = %s",
|
||||
(int(task["id"]), item_id))
|
||||
return item_id, True
|
||||
iid, made = self._mt_call(run)
|
||||
return self.get_meeting_task(item_id=iid), made # type: ignore[return-value]
|
||||
|
||||
def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
|
||||
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
|
||||
with self._pool.connection() as conn:
|
||||
|
||||
+330
-35
@@ -86,6 +86,19 @@ def _require_user(request: Request) -> dict[str, Any]:
|
||||
return user
|
||||
|
||||
|
||||
def _page_user(request: Request) -> Any:
|
||||
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
|
||||
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
|
||||
if get_current_user_record(request) is None:
|
||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
||||
return _require_user(request)
|
||||
|
||||
|
||||
def _require_pro(request: Request) -> dict[str, Any]:
|
||||
"""Pro user 이상(수퍼관리자·Admin·Pro user) — access.is_pro."""
|
||||
user = _require_user(request)
|
||||
@@ -130,15 +143,15 @@ def _accessible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
||||
return access.visible_project_ids(st, user)
|
||||
|
||||
|
||||
_TASK_DENIED = "이 작업을 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요."
|
||||
_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 작업이라 읽기만 할 수 있습니다. "
|
||||
_TASK_DENIED = "이 업무를 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요."
|
||||
_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 업무라 읽기만 할 수 있습니다. "
|
||||
"변경은 원 소속 프로젝트 멤버만 할 수 있습니다.")
|
||||
|
||||
|
||||
def _task_or_404(st: Any, task_id: int) -> dict[str, Any]:
|
||||
task = st.get_task(task_id=task_id)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
||||
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||
return task
|
||||
|
||||
|
||||
@@ -394,7 +407,7 @@ def _notify_completed(
|
||||
subject=store.build_subject_completed(project_name=project_name, task_title=task["title"]),
|
||||
body=(
|
||||
f"프로젝트: {project_name}\n"
|
||||
f"완료된 작업: {task['title']}\n"
|
||||
f"완료된 업무: {task['title']}\n"
|
||||
f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n"
|
||||
f"완료 처리: {actor}\n"
|
||||
),
|
||||
@@ -402,7 +415,7 @@ def _notify_completed(
|
||||
_inbox(
|
||||
st, recipients=_task_recipients(st, project, task, exclude=actor),
|
||||
actor=actor, project_id=task["project_id"], task_id=task["id"],
|
||||
ntype="completed", title=f"작업 완료: {task['title']}", body=project_name,
|
||||
ntype="completed", title=f"업무 완료: {task['title']}", body=project_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -636,7 +649,9 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _render_config_needed(request, user)
|
||||
@@ -667,8 +682,8 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"page_title": "내 작업",
|
||||
"page_subtitle": "내가 담당자인 작업을 한 곳에서 봅니다.",
|
||||
"page_title": "내 업무",
|
||||
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
|
||||
"force_sidebar_collapsed": True,
|
||||
"nav_projects": nav_projects,
|
||||
"goal_years": _goal_years_nav(st),
|
||||
@@ -728,11 +743,11 @@ def task_permalink(request: Request, task_id: int):
|
||||
|
||||
task = st.get_task(task_id=task_id)
|
||||
if task is None:
|
||||
return _denied("작업을 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
|
||||
return _denied("업무를 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
|
||||
target = _task_open_project(st, user, task)
|
||||
if target is None:
|
||||
return _denied(
|
||||
"이 작업이 속한 프로젝트의 멤버만 볼 수 있습니다. "
|
||||
"이 업무가 속한 프로젝트의 멤버만 볼 수 있습니다. "
|
||||
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
||||
403,
|
||||
)
|
||||
@@ -764,7 +779,9 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _render_config_needed(request, user)
|
||||
@@ -1448,6 +1465,18 @@ def api_my_tasks(request: Request) -> JSONResponse:
|
||||
return JSONResponse({"tasks": _my_visible_tasks(st, user)})
|
||||
|
||||
|
||||
@router.get("/api/my-overdue")
|
||||
def api_my_overdue(request: Request) -> JSONResponse:
|
||||
"""마감이 지난 내 미완료 업무(마감일이 오늘(한국시간) 이전) — ERP 모든 화면 위쪽 알림(static/erp-overdue.js)이 쓴다.
|
||||
지금 볼 수 있는 업무만, 마감이 오래된 것부터."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
today = today_kst()
|
||||
rows = access.filter_visible_tasks(st, user, st.list_my_overdue(assignee_email=user["email"], today=today))
|
||||
keys = ("id", "title", "due_date", "project_id", "project_name", "project_color", "parent_task_id", "parent_title")
|
||||
return JSONResponse({"today": today.isoformat(), "tasks": [{k: t.get(k) for k in keys} for t in rows]})
|
||||
|
||||
|
||||
@router.get("/api/my-tasks/open-count")
|
||||
def api_my_open_count(request: Request) -> JSONResponse:
|
||||
"""사이드바 "내 업무" 배지 숫자만 — 목록 전체를 받지 않는다."""
|
||||
@@ -1465,11 +1494,22 @@ def api_create_task(
|
||||
) -> JSONResponse:
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
task, skipped = _create_task_for(request, st, user, project_id, payload, bg)
|
||||
return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201)
|
||||
|
||||
|
||||
def _create_task_for(
|
||||
request: Request, st: Any, user: dict[str, Any], project_id: int, payload: dict[str, Any],
|
||||
bg: BackgroundTasks,
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
"""작업 만들기 공통(작업 창·회의록 작업 등록 [적용]) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
|
||||
돌려주는 값: (작업, 태그하지 못한 이메일)."""
|
||||
_require_manage(request, st, user, project_id)
|
||||
project = st.get_project(project_id=project_id)
|
||||
if project is None:
|
||||
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||
_check_assignee(st, payload.get("assignee_email"), project_id)
|
||||
followers = _check_followers(st, payload.get("followers"), project_id)
|
||||
try:
|
||||
task = st.create_task(
|
||||
project_id=project_id,
|
||||
@@ -1491,8 +1531,10 @@ def api_create_task(
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
# 만든 사람·담당자는 자동 팔로워(아사나와 같은 규칙)
|
||||
_follow(st, task["id"], [user["email"], task.get("assignee_email") or ""])
|
||||
# 만든 사람은 자동 협업자 + 만들 때 고른 협업자(세부 업무 추가 칸 등). 담당자는 협업자가 아니다(2026-10-13,
|
||||
# db.add_followers 가 담당자를 거른다 — 만든 사람이 담당자여도 빠진다).
|
||||
# 세부 업무는 만든 사람을 자동으로 넣지 않는다 — 고른 협업자만(2026-10-14 사용자 요청).
|
||||
_follow(st, task["id"], ([] if task.get("parent_task_id") else [user["email"]]) + followers)
|
||||
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
|
||||
if task.get("assignee_email"):
|
||||
_notify(
|
||||
@@ -1504,7 +1546,7 @@ def api_create_task(
|
||||
),
|
||||
body=(
|
||||
f"프로젝트: {project['name']}\n"
|
||||
f"작업: {task['title']}\n"
|
||||
f"업무: {task['title']}\n"
|
||||
f"담당자: {task.get('assignee_name') or task['assignee_email']} "
|
||||
f"({task['assignee_email']})\n"
|
||||
f"마감일: {task.get('due_date') or '-'}\n"
|
||||
@@ -1514,7 +1556,7 @@ def api_create_task(
|
||||
_inbox(
|
||||
st, recipients=[task["assignee_email"]], actor=user["email"],
|
||||
project_id=project_id, task_id=task["id"], ntype="assigned",
|
||||
title=f"작업 배정: {task['title']}",
|
||||
title=f"업무 배정: {task['title']}",
|
||||
body=f"{project['name']} · 마감 {task.get('due_date') or '-'}",
|
||||
)
|
||||
# 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림.
|
||||
@@ -1525,12 +1567,25 @@ def api_create_task(
|
||||
emails=store.extract_mentions_from_html(task.get("description") or ""),
|
||||
actor=user["email"], project_name=project["name"],
|
||||
)
|
||||
return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201)
|
||||
return task, skipped
|
||||
|
||||
|
||||
_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
|
||||
|
||||
|
||||
def _check_followers(st: Any, raw: Any, project_id: int) -> list[str]:
|
||||
"""업무를 만들 때 같이 고른 협업자 — 협업자 추가 API 와 같은 기준(그 프로젝트를 볼 수 있는 사람만, 아니면 400)."""
|
||||
if not raw:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise HTTPException(status_code=400, detail="협업자 목록이 올바르지 않습니다.")
|
||||
emails = store.normalize_emails([str(e) for e in raw])
|
||||
for em in emails:
|
||||
if not access.can_assign(st, em, project_id):
|
||||
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
||||
return emails
|
||||
|
||||
|
||||
def _check_assignee(st: Any, email: Any, project_id: int, *, previous: str = "") -> None:
|
||||
"""새로 지정하는 담당자가 그 프로젝트를 볼 수 있는지 — 권한 없는 사람에게 배정 알림(작업 제목
|
||||
등)이 가지 않게. 비우거나 그대로 두는 건 검사하지 않는다(멤버에서 빠진 예전 담당자 보존)."""
|
||||
@@ -1563,12 +1618,11 @@ def api_update_task(
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
||||
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||
|
||||
project_name = task.get("project_name") or ""
|
||||
project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name}
|
||||
if task.get("_newly_assigned"):
|
||||
_follow(st, task_id, [task["_newly_assigned"]])
|
||||
if task.get("_newly_assigned"): # 담당자는 협업자가 아니다 — db.update_task 가 협업자에서 뺐다(2026-10-13)
|
||||
_notify(
|
||||
bg, request,
|
||||
subject=store.build_subject_assigned(
|
||||
@@ -1578,7 +1632,7 @@ def api_update_task(
|
||||
),
|
||||
body=(
|
||||
f"프로젝트: {project_name}\n"
|
||||
f"작업: {task['title']}\n"
|
||||
f"업무: {task['title']}\n"
|
||||
f"담당자: {task.get('assignee_name') or task['_newly_assigned']} "
|
||||
f"({task['_newly_assigned']})\n"
|
||||
f"마감일: {task.get('due_date') or '-'}\n"
|
||||
@@ -1588,7 +1642,7 @@ def api_update_task(
|
||||
_inbox(
|
||||
st, recipients=[task["_newly_assigned"]], actor=user["email"],
|
||||
project_id=existing["project_id"], task_id=task_id, ntype="assigned",
|
||||
title=f"작업 배정: {task['title']}",
|
||||
title=f"업무 배정: {task['title']}",
|
||||
body=f"{project_name} · 마감 {task.get('due_date') or '-'}",
|
||||
)
|
||||
if task.get("_newly_completed"):
|
||||
@@ -1613,7 +1667,7 @@ def api_delete_task(request: Request, task_id: int) -> JSONResponse:
|
||||
try:
|
||||
removed_task_ids, trash_id = st.delete_task(task_id=task_id, deleted_by=user["email"])
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
||||
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||
# 휴지통(010)이 있으면 첨부 폴더도 휴지통으로(복구 대비), 없으면 예전처럼 삭제.
|
||||
if trash_id is not None:
|
||||
_move_task_dirs_to_trash(request, removed_task_ids, trash_id)
|
||||
@@ -1648,6 +1702,10 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse:
|
||||
else:
|
||||
try:
|
||||
task["followers"] = st.list_followers(task_id=task_id)
|
||||
# 세부 업무 줄의 협업자 아이콘(담당자 오른쪽) — 줄마다 다시 묻지 않게 한 번에.
|
||||
by_sub = st.list_followers_of(task_ids=[s["id"] for s in task["subtasks"]])
|
||||
for s in task["subtasks"]:
|
||||
s["followers"] = by_sub.get(int(s["id"]), [])
|
||||
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
|
||||
task["followers"] = None
|
||||
return JSONResponse({"task": task})
|
||||
@@ -1700,6 +1758,59 @@ def api_move_subtask(
|
||||
return JSONResponse({"task": task})
|
||||
|
||||
|
||||
@router.post("/api/tasks/{task_id}/move-project")
|
||||
def api_move_task_project(
|
||||
request: Request,
|
||||
task_id: int,
|
||||
bg: BackgroundTasks,
|
||||
payload: dict[str, Any] = Body(...),
|
||||
) -> JSONResponse:
|
||||
"""메인 업무를 다른 프로젝트로 옮긴다 — 보드 카드·목록 줄을 왼쪽 프로젝트 목록으로 드래그 → 섹션 선택 창.
|
||||
|
||||
body: {"project_id": 대상, "stage_id": 대상 섹션 또는 null}. 원 소속 권한(FULL) + 대상 프로젝트 멤버여야 한다.
|
||||
세부 업무는 함께 옮겨진다. 응답의 `unseen` = 대상 프로젝트를 볼 수 없는 담당자·협업자(화면이 안내).
|
||||
"""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
existing = _task_or_404(st, task_id)
|
||||
_require_task(st, user, existing, write=True)
|
||||
try:
|
||||
target = int(payload.get("project_id"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="옮길 프로젝트(project_id)가 필요합니다.")
|
||||
_require_manage(request, st, user, target)
|
||||
project = st.get_project(project_id=target)
|
||||
if project is None:
|
||||
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||
try:
|
||||
task = st.move_task_to_project(
|
||||
task_id=task_id, project_id=target, stage_id=payload.get("stage_id"),
|
||||
actor=user["email"], assignee_allowed=_registered_project_user,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
task.pop("_moved_ids", None)
|
||||
newly_assigned = task.pop("_newly_assigned", None)
|
||||
if newly_assigned: # 대상 섹션 기본 담당자가 자동 배정됨 — 일반 배정과 같은 알림(담당자는 협업자가 아님)
|
||||
_inbox(
|
||||
st, recipients=[newly_assigned], actor=user["email"], project_id=target, task_id=task["id"],
|
||||
ntype="assigned", title=f"업무 배정: {task['title']}",
|
||||
body=f"{project['name']} · 마감 {task.get('due_date') or '-'}",
|
||||
)
|
||||
if task.pop("_newly_completed", False):
|
||||
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
|
||||
people = [task.get("assignee_email") or ""]
|
||||
try:
|
||||
people += st.list_followers(task_id=task_id)
|
||||
except Exception: # noqa: BLE001 - 008 미적용
|
||||
pass
|
||||
unseen = sorted({store.norm_str(e, lower=True) for e in people if e} -
|
||||
set(access.filter_recipients(st, task, [e for e in people if e])))
|
||||
return JSONResponse({"task": task, "unseen": unseen})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# JSON API — 팔로워 (아사나의 협업자)
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@@ -1735,6 +1846,8 @@ def api_add_follower(
|
||||
st = _db_or_503(request)
|
||||
task = _task_for_followers(request, st, user, task_id)
|
||||
email = store.norm_str(payload.get("email") or user["email"], lower=True)
|
||||
if email and email == store.norm_str(task.get("assignee_email") or "", lower=True):
|
||||
raise HTTPException(status_code=400, detail="담당자는 협업자로 지정할 수 없습니다(협업자는 담당자 외의 멤버).")
|
||||
if email != store.norm_str(user["email"], lower=True):
|
||||
if not access.can_assign(st, email, task["project_id"]):
|
||||
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
||||
@@ -1827,13 +1940,13 @@ def api_add_task_link(
|
||||
st = _db_or_503(request)
|
||||
task = st.get_task(task_id=task_id)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
||||
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||
try:
|
||||
target_project_id = int(payload.get("project_id"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="project_id 가 필요합니다.")
|
||||
if target_project_id == task["project_id"]:
|
||||
raise HTTPException(status_code=400, detail="이미 이 작업의 기본 프로젝트입니다.")
|
||||
raise HTTPException(status_code=400, detail="이미 이 업무의 기본 프로젝트입니다.")
|
||||
_require_manage(request, st, user, target_project_id)
|
||||
already_linked = any(
|
||||
link["project_id"] == target_project_id for link in st.list_task_links(task_id=task_id)
|
||||
@@ -1859,7 +1972,7 @@ def api_remove_task_link(request: Request, task_id: int, project_id: int) -> JSO
|
||||
st = _db_or_503(request)
|
||||
task = st.get_task(task_id=task_id)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
||||
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||
_require_manage(request, st, user, task["project_id"])
|
||||
_require_manage(request, st, user, project_id)
|
||||
st.remove_task_link(task_id=task_id, project_id=project_id)
|
||||
@@ -2115,9 +2228,31 @@ def api_toggle_reaction(
|
||||
reactions = st.toggle_reaction(comment_id=comment_id, user_email=user["email"], emoji=emoji)
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
|
||||
me = store.norm_str(user["email"], lower=True)
|
||||
if any(r["emoji"] == emoji and me in r["users"] for r in reactions): # 켤 때만(끌 때는 알림 없음)
|
||||
_notify_reaction(st, task=task, comment=comment, actor=user["email"], emoji=emoji)
|
||||
return JSONResponse({"reactions": reactions})
|
||||
|
||||
|
||||
def _notify_reaction(
|
||||
st: Any, *, task: dict[str, Any], comment: dict[str, Any], actor: str, emoji: str,
|
||||
) -> None:
|
||||
"""댓글 이모티콘 반응 알림 — 그 댓글을 쓴 사람에게 어떤 이모티콘인지(자기 댓글·지금 볼 수 없는 사람은 제외)."""
|
||||
author = store.norm_str(comment.get("author_email"), lower=True)
|
||||
if not author or author == store.norm_str(actor, lower=True):
|
||||
return
|
||||
recipients = access.filter_recipients(st, task, [author])
|
||||
if not recipients:
|
||||
return
|
||||
project = st.get_project(project_id=task["project_id"]) or {}
|
||||
preview = (comment.get("body") or "").strip().replace("\n", " ")[:80] or "첨부 파일"
|
||||
_inbox(
|
||||
st, recipients=recipients, actor=actor, project_id=task["project_id"], task_id=task["id"],
|
||||
ntype="reaction", title=f"내 댓글에 {emoji} 반응: {task['title']}",
|
||||
body=f"{project.get('name') or task.get('project_name') or ''} · “{preview}”",
|
||||
)
|
||||
|
||||
|
||||
def _comment_task_access(st: Any, user: dict[str, Any], comment_id: int) -> dict[str, Any]:
|
||||
"""댓글 수정·삭제 전 — 작성자라도 지금 그 작업의 원 소속 권한이 없으면 거절(멤버에서 빠진 뒤
|
||||
자기 댓글을 고치거나 지우던 경로 차단). 작성자 본인/관리자 검사는 DB 쪽이 한다."""
|
||||
@@ -2585,7 +2720,7 @@ def notifier_page(request: Request) -> Any:
|
||||
"my_open_total": _my_open_count(st, user),
|
||||
"mention_unread": _safe_mention_unread(st, user),
|
||||
"page_title": "PC 알림 프로그램",
|
||||
"page_subtitle": "브라우저가 뒤에 있어도 태그·작업 배정 알림을 화면 위에 크게",
|
||||
"page_subtitle": "브라우저가 뒤에 있어도 태그·업무 배정 알림을 화면 위에 크게",
|
||||
"force_sidebar_collapsed": True,
|
||||
"color_palette": list(store.COLOR_PALETTE),
|
||||
"project_icons": list(store.PROJECT_ICONS),
|
||||
@@ -2714,7 +2849,9 @@ def trash_page(request: Request) -> HTMLResponse:
|
||||
"""휴지통 — Pro user 이상. 지운 업무(세부 업무 포함)를 3개월 보관, 복구(멤버인 프로젝트 것만)."""
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
if not access.is_pro(user):
|
||||
raise HTTPException(status_code=403, detail="Pro user 이상만 볼 수 있습니다.")
|
||||
st = _store(request)
|
||||
@@ -2734,7 +2871,7 @@ def trash_page(request: Request) -> HTMLResponse:
|
||||
"my_open_total": _my_open_count(st, user),
|
||||
"mention_unread": _safe_mention_unread(st, user),
|
||||
"page_title": "휴지통",
|
||||
"page_subtitle": "삭제한 작업 — 3개월 보관, Pro user 이상만 복구",
|
||||
"page_subtitle": "삭제한 업무 — 3개월 보관, Pro user 이상만 복구",
|
||||
"force_sidebar_collapsed": True,
|
||||
"color_palette": list(store.COLOR_PALETTE),
|
||||
"project_icons": list(store.PROJECT_ICONS),
|
||||
@@ -2796,7 +2933,9 @@ def help_page(request: Request) -> HTMLResponse:
|
||||
DB 없이 그리는 정적 안내라 DB 설정 전에도 열린다."""
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
return render_template(
|
||||
request,
|
||||
"project/help.html",
|
||||
@@ -2815,7 +2954,9 @@ def inbox_page(request: Request) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _render_config_needed(request, user)
|
||||
@@ -2839,7 +2980,7 @@ def inbox_page(request: Request) -> HTMLResponse:
|
||||
"goal_years": _goal_years_nav(st),
|
||||
"my_open_total": my_open_total,
|
||||
"page_title": "수신함",
|
||||
"page_subtitle": "나를 태그한 작업과 프로젝트 알림",
|
||||
"page_subtitle": "나를 태그한 업무와 프로젝트 알림",
|
||||
"force_sidebar_collapsed": True,
|
||||
"color_palette": list(store.COLOR_PALETTE),
|
||||
"project_icons": list(store.PROJECT_ICONS),
|
||||
@@ -2914,6 +3055,20 @@ def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
|
||||
row["layout"] = out
|
||||
|
||||
|
||||
def _meeting_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||
"""회의록 구역 한 덩어리의 항목 칸 묶음(027) — 이어 붙은 줄(label_cont, 구역 첫 줄 제외)은 항목 칸을 그리지 않고
|
||||
(label_hidden) 묶음 첫 줄이 rowspan(label_span). label_shown = 그 줄이 속한 항목 이름(칸 이름표·접근성용)."""
|
||||
grp: dict[str, Any] | None = None
|
||||
for i, it in enumerate(rows):
|
||||
if i and it.get("label_cont") and grp is not None:
|
||||
it["label_hidden"] = True
|
||||
grp["label_span"] += 1
|
||||
else:
|
||||
grp = it
|
||||
it["label_hidden"], it["label_span"] = False, 1
|
||||
it["label_shown"] = grp["label"]
|
||||
|
||||
|
||||
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
|
||||
영역 첫 줄은 늘 묶음 첫 줄."""
|
||||
@@ -2946,6 +3101,12 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
||||
raise HTTPException(status_code=409, detail="회의가 완료되어 수정할 수 없습니다. 관리자가 [완료 해제]하면 다시 고칠 수 있습니다.")
|
||||
except store.MeetingMigration022Needed:
|
||||
raise HTTPException(status_code=503, detail="회의 완료 기능은 project_db 마이그레이션 022 적용 후 사용할 수 있습니다.")
|
||||
except store.MeetingMigration027Needed:
|
||||
raise HTTPException(status_code=503, detail="같은 항목 칸 안 줄 추가·항목 칸 나누기는 project_db 마이그레이션 027 적용 후 사용할 수 있습니다.")
|
||||
except store.MeetingParentTaskMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail="업무 칸(이미 있는 업무의 세부 업무로 등록)은 project_db 마이그레이션 026 적용 후 사용할 수 있습니다.")
|
||||
except store.MeetingTaskMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail="업무 등록 표(모두가 같이 보는 주차별 표)는 project_db 마이그레이션 025 적용 후 사용할 수 있습니다.")
|
||||
except store.MeetingMigration020Needed:
|
||||
raise HTTPException(status_code=503, detail="새 주차·결과 글·주차별 목표는 project_db 마이그레이션 020 적용 후 사용할 수 있습니다.")
|
||||
except store.GoalCellConflict as exc:
|
||||
@@ -2961,7 +3122,9 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
||||
@router.get("/goals")
|
||||
def goals_home(request: Request) -> RedirectResponse:
|
||||
"""사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로."""
|
||||
_require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
years = _goal_years_nav(st) if st is not None else [today_kst().year]
|
||||
return RedirectResponse(url=f"/project/goals/{years[0]}", status_code=303)
|
||||
@@ -2974,7 +3137,9 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _render_config_needed(request, user)
|
||||
@@ -3426,6 +3591,7 @@ def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: dat
|
||||
meeting["sections"] = sections
|
||||
for sec in sections:
|
||||
covered = 0
|
||||
_meeting_label_spans(sec["rows"])
|
||||
for i, it in enumerate(sec["rows"]):
|
||||
it["content_html"] = store.goal_text_html(it["content"])
|
||||
it["content_hidden"] = covered > 0
|
||||
@@ -3505,7 +3671,9 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _render_config_needed(request, user)
|
||||
@@ -3669,7 +3837,8 @@ def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
|
||||
|
||||
@router.post("/api/goals/meetings/{week_start}/items")
|
||||
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""줄 추가 {section, label?, ref_item_id?, place?: above|below} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝)."""
|
||||
"""줄 추가 {section, label?, ref_item_id?, place?: above|below, same_label?} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝).
|
||||
same_label = 주요 업무 칸에서 추가 — 기준 줄과 같은 항목 칸 안에(027)."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
ws = _goal_call(store.validate_week_start, week_start)
|
||||
@@ -3681,6 +3850,7 @@ def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, A
|
||||
item_id = _goal_call(
|
||||
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
|
||||
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
|
||||
same_label=bool(payload.get("same_label")),
|
||||
)
|
||||
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
|
||||
|
||||
@@ -3737,3 +3907,128 @@ def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any
|
||||
st = _db_or_503(request)
|
||||
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/goals/meeting-items/{item_id}/split-label")
|
||||
def api_split_meeting_label(request: Request, item_id: int) -> JSONResponse:
|
||||
"""항목 칸 나누기(027) — item_id = 묶음 첫 줄. 이어 붙은 줄들이 각자 항목 칸(이름 빈 칸)으로. 줄 순서와 같은 권한."""
|
||||
_require_user(request)
|
||||
n = _goal_call(_db_or_503(request).split_meeting_label, item_id=item_id)
|
||||
return JSONResponse({"ok": True, "split": n})
|
||||
|
||||
|
||||
# ── 회의록 작업 등록 표(025) — 주차별 한 표를 서버에(예전엔 각자 브라우저에만 있어 다른 사람 줄이 안 보였다) ──
|
||||
# 보기·고치기: 회의록을 볼 수 있는 사람 누구나(회의 완료면 잠금). 줄에 고른 프로젝트는 내가 멤버인 것만 고를 수 있고,
|
||||
# 내가 멤버가 아닌 프로젝트를 가리키는 남의 줄은 프로젝트·섹션 이름·만든 작업을 가린다. [적용] = 그 프로젝트 멤버만.
|
||||
def _quick_view(st: Any, user: dict[str, Any], rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
seen: dict[int, bool] = {}
|
||||
out = []
|
||||
for r in rows:
|
||||
pid = r.get("project_id")
|
||||
ok = True if pid is None else seen.setdefault(pid, access.can_manage_project(st, user, pid))
|
||||
r = dict(r, visible=ok, registered=r.get("task_id") is not None) # 등록됨 여부는 누구에게나(작업 내용은 멤버만)
|
||||
if not ok:
|
||||
r.update(project_name="(볼 수 없는 프로젝트)", stage_name="", task_title="", task_id=None,
|
||||
task_project_id=None, parent_task_id=None, parent_task_title="")
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def _quick_fields(st: Any, user: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
|
||||
fields = {k: payload[k] for k in ("title", "assignee_email", "project_id", "stage_id", "parent_task_id") if k in payload}
|
||||
pid = fields.get("project_id")
|
||||
if pid not in (None, ""):
|
||||
try:
|
||||
pid = int(pid)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="프로젝트 값이 올바르지 않습니다.")
|
||||
if not access.can_manage_project(st, user, pid):
|
||||
raise HTTPException(status_code=403, detail="내가 멤버인 프로젝트만 고를 수 있습니다.")
|
||||
return fields
|
||||
|
||||
|
||||
@router.get("/api/goals/meetings/{week_start}/quick-tasks")
|
||||
def api_list_quick_tasks(request: Request, week_start: str) -> JSONResponse:
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
ws = _goal_call(store.validate_week_start, week_start)
|
||||
rows = _goal_call(st.list_meeting_tasks, week_start=ws)
|
||||
return JSONResponse({"tasks": _quick_view(st, user, rows)})
|
||||
|
||||
|
||||
@router.post("/api/goals/meetings/{week_start}/quick-tasks")
|
||||
def api_add_quick_task(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""줄 추가 {title?, assignee_email?, project_id?, stage_id?, parent_task_id?(작업 칸 — 그 작업의 세부 작업으로),
|
||||
task_id?(예전 브라우저 표의 등록된 줄)}."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
ws = _goal_call(store.validate_week_start, week_start)
|
||||
fields = _quick_fields(st, user, payload)
|
||||
task_id = None
|
||||
if payload.get("task_id") not in (None, ""):
|
||||
# 옮겨 오는 등록된 줄 — 그 작업을 지금 내가 원 소속으로 다룰 수 있을 때만 이어 붙인다(남의 작업 id 를 끌어오지 못하게)
|
||||
try:
|
||||
t = st.get_task(task_id=int(payload["task_id"]))
|
||||
except (TypeError, ValueError):
|
||||
t = None
|
||||
if t is not None and access.task_access(st, user, t) == access.FULL:
|
||||
task_id = int(t["id"])
|
||||
row = _goal_call(st.add_meeting_task, week_start=ws, fields=fields, by=user["email"], task_id=task_id)
|
||||
return JSONResponse({"task": _quick_view(st, user, [row])[0]}, status_code=201)
|
||||
|
||||
|
||||
@router.put("/api/goals/meeting-quick-tasks/{item_id}")
|
||||
def api_update_quick_task(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
fields = _quick_fields(st, user, payload)
|
||||
row = _goal_call(st.update_meeting_task, item_id=item_id, fields=fields, by=user["email"])
|
||||
return JSONResponse({"task": _quick_view(st, user, [row])[0]})
|
||||
|
||||
|
||||
@router.delete("/api/goals/meeting-quick-tasks/{item_id}")
|
||||
def api_delete_quick_task(request: Request, item_id: int) -> JSONResponse:
|
||||
"""줄 지우기. 이미 만든 작업은 화면이 따로 지운다(DELETE /api/tasks/{id} — 그 프로젝트 멤버만, 휴지통)."""
|
||||
_require_user(request)
|
||||
st = _db_or_503(request)
|
||||
_goal_call(st.delete_meeting_task, item_id=item_id)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/goals/meeting-quick-tasks/{item_id}/apply")
|
||||
def api_apply_quick_task(request: Request, item_id: int, bg: BackgroundTasks) -> JSONResponse:
|
||||
"""[적용] — 그 줄로 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림). 줄을 잠그고 한 번만 — 이미 만들었으면 그 결과."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
|
||||
def create(row: dict[str, Any], parent_task_id: int | None) -> dict[str, Any]:
|
||||
if not row["title"].strip():
|
||||
raise ValueError("업무 제목을 쓰세요.")
|
||||
if row["project_id"] is None:
|
||||
raise ValueError("프로젝트를 고르세요.")
|
||||
rec = access.default_user_lookup(row["assignee_email"]) if row["assignee_email"] else None
|
||||
# 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — _create_task_for 가 프로젝트 멤버를, create_task 가 같은 프로젝트를 확인
|
||||
payload = {"title": row["title"].strip(), "stage_id": None if parent_task_id else row["stage_id"],
|
||||
"assignee_email": row["assignee_email"],
|
||||
"assignee_name": (rec or {}).get("name") or (row["assignee_email"].split("@")[0] if row["assignee_email"] else ""),
|
||||
"parent_task_id": parent_task_id}
|
||||
return _create_task_for(request, st, user, int(row["project_id"]), payload, bg)[0]
|
||||
|
||||
row, made = _goal_call(st.apply_meeting_task, item_id=item_id, create=create)
|
||||
return JSONResponse({"task": _quick_view(st, user, [row])[0], "created": made}, status_code=201 if made else 200)
|
||||
|
||||
|
||||
@router.post("/api/goals/meeting-items/{item_id}/move-section")
|
||||
def api_move_meeting_section(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""구역(첫 열 "구분") 통째로 위/아래 {direction: -1|1} — item_id = 그 구역의 아무 줄. 줄 순서와 같은 권한(누구나,
|
||||
회의 완료 전까지). 다음 회의록은 이 순서를 이어받는다."""
|
||||
_require_user(request)
|
||||
st = _db_or_503(request)
|
||||
try:
|
||||
direction = int(payload.get("direction") or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="direction 이 올바르지 않습니다.")
|
||||
if direction not in (-1, 1):
|
||||
raise HTTPException(status_code=400, detail="direction 은 -1(위) 또는 1(아래)입니다.")
|
||||
_goal_call(st.move_meeting_section, item_id=item_id, direction=direction)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
@@ -41,6 +41,7 @@ ACTION_COMPLETED = "completed"
|
||||
ACTION_STAGE_CHANGED = "stage_changed"
|
||||
ACTION_REOPENED = "reopened"
|
||||
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
|
||||
ACTION_PROJECT_MOVED = "project_moved" # 업무를 다른 프로젝트로 옮김(왼쪽 프로젝트 목록으로 드래그)
|
||||
|
||||
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
||||
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
||||
@@ -283,9 +284,9 @@ def validate_project_name(name: Any) -> str:
|
||||
def validate_task_title(title: Any) -> str:
|
||||
v = norm_str(title)
|
||||
if not v:
|
||||
raise ValueError("작업 제목은 필수입니다.")
|
||||
raise ValueError("업무 제목은 필수입니다.")
|
||||
if len(v) > 300:
|
||||
raise ValueError("작업 제목이 너무 깁니다(300자 이내).")
|
||||
raise ValueError("업무 제목이 너무 깁니다(300자 이내).")
|
||||
return v
|
||||
|
||||
|
||||
@@ -431,6 +432,18 @@ class MeetingMigration022Needed(RuntimeError):
|
||||
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
|
||||
|
||||
|
||||
class MeetingMigration027Needed(RuntimeError):
|
||||
"""같은 항목 칸 안 줄 추가·항목 칸 나누기(goal_meeting_items.label_cont)는 마이그레이션 027 뒤에만 된다."""
|
||||
|
||||
|
||||
class MeetingTaskMigrationNeeded(RuntimeError):
|
||||
"""회의록 작업 등록 표(서버 저장)는 마이그레이션 025 뒤에만 된다."""
|
||||
|
||||
|
||||
class MeetingParentTaskMigrationNeeded(RuntimeError):
|
||||
"""작업 등록 표의 작업 칸(이미 있는 작업의 세부 작업으로)은 마이그레이션 026 뒤에만 된다."""
|
||||
|
||||
|
||||
class MeetingMigration020Needed(RuntimeError):
|
||||
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
|
||||
|
||||
@@ -813,11 +826,11 @@ def sales_unit_multiplier(unit: str) -> int | None:
|
||||
|
||||
|
||||
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
||||
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
||||
return f"[DBX 프로젝트] 업무 배정: {project_name} · {task_title} → {assignee}"
|
||||
|
||||
|
||||
def build_subject_completed(*, project_name: str, task_title: str) -> str:
|
||||
return f"[DBX 프로젝트] 작업 완료: {project_name} · {task_title}"
|
||||
return f"[DBX 프로젝트] 업무 완료: {project_name} · {task_title}"
|
||||
|
||||
|
||||
def build_subject_project_done(*, project_name: str) -> str:
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{# 설명란 서식 도구(작업 창·긴급 공지 관리 공용). fmtbar_id·img_input_id 를 주면 그 id 로(기본 = 작업 창 id).
|
||||
동작은 project.js createDescEditor — 버튼 data-cmd 를 그대로 쓴다. #}
|
||||
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
||||
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
||||
<div class="pj-desc-fmtbar" id="{{ fmtbar_id or 'pj-desc-fmtbar' }}">
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
||||
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<label class="pj-desc-fmtbtn" id="{{ (fmtbar_id ~ '-imgbtn') if fmtbar_id else 'pj-desc-imgbtn' }}" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="{{ img_input_id or 'pj-desc-img-input' }}" accept="image/*" hidden /></label>
|
||||
</div>
|
||||
@@ -2,12 +2,12 @@
|
||||
project.js initMemberTasks() 가 배선. project/mytasks/inbox 공용. #}
|
||||
<div class="pj-modal" id="pj-modal-member-tasks" hidden>
|
||||
<div class="pj-modal-card pj-mt-card">
|
||||
<h3 id="pj-mt-title">작업</h3>
|
||||
<p class="pj-modal-hint">더블클릭하면 작업 편집 창이 열립니다.</p>
|
||||
<h3 id="pj-mt-title">업무</h3>
|
||||
<p class="pj-modal-hint">더블클릭하면 업무 편집 창이 열립니다.</p>
|
||||
<div class="pj-mt-head" id="pj-mt-head">
|
||||
<span class="pj-mt-h" data-sort="project">프로젝트<span class="pj-mt-sort-icon"></span></span>
|
||||
<span class="pj-mt-h" data-sort="stage">섹션<span class="pj-mt-sort-icon"></span></span>
|
||||
<span class="pj-mt-h" data-sort="title">작업<span class="pj-mt-sort-icon"></span></span>
|
||||
<span class="pj-mt-h" data-sort="title">업무<span class="pj-mt-sort-icon"></span></span>
|
||||
<span class="pj-mt-h" data-sort="due">마감일<span class="pj-mt-sort-icon"></span></span>
|
||||
</div>
|
||||
<ul class="pj-mt-list" id="pj-mt-list"></ul>
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
</select>
|
||||
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
|
||||
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p>
|
||||
{% if user and user.is_super_admin %}<p class="pj-options-notice"><a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 긴급 공지 만들기·관리</a> <small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></p>{% endif %}
|
||||
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
||||
<div class="pj-options-actions">
|
||||
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
||||
<div class="pj-side-search">
|
||||
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
||||
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="작업 전체 검색" />
|
||||
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="업무 전체 검색" />
|
||||
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
||||
</div>
|
||||
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
||||
@@ -52,7 +52,7 @@
|
||||
{% endif %}
|
||||
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
||||
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
||||
<span class="pj-side-navtext">내 작업</span>
|
||||
<span class="pj-side-navtext">내 업무</span>
|
||||
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
||||
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
||||
</a>
|
||||
|
||||
@@ -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=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -116,11 +116,14 @@
|
||||
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
|
||||
</section>
|
||||
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick">
|
||||
<h3>작업 등록 <small>제목을 쓰고 담당자·프로젝트·섹션 칸을 눌러 고른 뒤 [적용]</small></h3>
|
||||
{# 작업 등록 — 주차마다 한 표를 서버에(025, 모두가 같은 표 — project.js initMeetQuickTasks). 제목 = "N주차 작업 등록", 회의 완료면 읽기 전용 #}
|
||||
{% set qw = weeks | selectattr("start", "equalto", week) | first %}
|
||||
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick" data-week="{{ week }}"{% if qw and qw.now %} data-now="1"{% endif %}{% if meeting and meeting.completed %} data-locked="1"{% endif %}>
|
||||
<h3>{% if week_n %}<span class="pj-meet-quick-week">{{ week_n }}주차</span> {% endif %}업무 등록
|
||||
<button type="button" class="pj-btn pj-btn-sm pj-meet-quick-expand" data-quick="expand" title="넓은 창에서 업무·세부 업무 등록(같은 표)"><span class="material-symbols-outlined">open_in_full</span>크게 열기</button></h3>
|
||||
<div class="pj-meet-area-body">
|
||||
<table class="pj-meet-quick-table">
|
||||
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th></th></tr></thead>
|
||||
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th title="고르면 그 업무의 세부 업무로 등록(비우면 섹션에 새 업무)">업무</th><th></th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
|
||||
@@ -224,21 +227,25 @@
|
||||
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
|
||||
{% for it in sec.rows %}
|
||||
{% set p = it.prev %}
|
||||
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}" data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
||||
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}"{% if it.label_hidden %} data-label-cont="1"{% endif %} data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
||||
{% if loop.first %}
|
||||
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
|
||||
{% if edit %}<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
||||
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more pj-meet-sec-more" data-meet-act="sec-menu" title="구역 메뉴(위로·아래로) · 우클릭도 됩니다"><span class="material-symbols-outlined">more_horiz</span></button>
|
||||
<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
||||
</th>
|
||||
{% endif %}
|
||||
<th class="pj-meet-c-label">
|
||||
{# 항목 칸 — 같은 항목 칸 안에 이어 붙은 줄(027 label_cont)은 그리지 않고 묶음 첫 줄이 rowspan #}
|
||||
{% if not it.label_hidden %}
|
||||
<th class="pj-meet-c-label"{% if (it.label_span or 1) > 1 %} rowspan="{{ it.label_span }}"{% endif %}>
|
||||
<span class="pj-meet-label-line">
|
||||
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||
</span>
|
||||
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
||||
</th>
|
||||
{% endif %}
|
||||
{% if not it.content_hidden %}
|
||||
<td class="pj-meet-c-text" rowspan="{{ it.content_span or 1 }}" data-meet-item="{{ it.id }}">
|
||||
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
||||
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
||||
{% else %}<div class="pj-meet-ro">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
@@ -251,7 +258,7 @@
|
||||
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{% if p.content_html is defined %}{{ p.content_html | safe }}{% else %}{{ p.content }}{% endif %}</div></td>
|
||||
{# 결과(글) — 지난 주차 줄의 result_note(020). 미적용이면 보기만 #}
|
||||
<td class="pj-meet-c-text is-prev pj-meet-c-note">
|
||||
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
||||
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
||||
{% else %}<div class="pj-meet-ro">{{ p.result_note or '' }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="pj-meet-c-amt is-prev">{{ p.target_text or won(p.target_amount) }}</td>
|
||||
@@ -290,6 +297,6 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<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=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -20,16 +20,16 @@
|
||||
<li><a href="#roles">누가 무엇을 할 수 있나요</a></li>
|
||||
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
||||
<li><a href="#views">보기 전환과 필터</a></li>
|
||||
<li><a href="#board">보드 — 섹션과 작업 카드</a></li>
|
||||
<li><a href="#card-subtasks">카드에서 세부 작업 다루기</a></li>
|
||||
<li><a href="#task">작업 편집 창</a></li>
|
||||
<li><a href="#subtasks">작업 창의 세부 작업</a></li>
|
||||
<li><a href="#board">보드 — 섹션과 업무 카드</a></li>
|
||||
<li><a href="#card-subtasks">카드에서 세부 업무 다루기</a></li>
|
||||
<li><a href="#task">업무 편집 창</a></li>
|
||||
<li><a href="#subtasks">업무 창의 세부 업무</a></li>
|
||||
<li><a href="#dates">날짜 고르기</a></li>
|
||||
<li><a href="#list">목록 보기</a></li>
|
||||
<li><a href="#calendar">캘린더 보기</a></li>
|
||||
<li><a href="#timeline">타임라인 보기</a></li>
|
||||
<li><a href="#dashboard">대시보드</a></li>
|
||||
<li><a href="#mytasks">내 작업</a></li>
|
||||
<li><a href="#mytasks">내 업무</a></li>
|
||||
<li><a href="#comments">댓글과 @태그</a></li>
|
||||
<li><a href="#inbox">수신함과 알림</a></li>
|
||||
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
||||
@@ -59,11 +59,11 @@
|
||||
<header class="pjh-hero">
|
||||
<h1>프로젝트 관리 도움말</h1>
|
||||
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
||||
프로젝트 안에 할 일(작업)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
||||
프로젝트 안에 할 일(업무)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
||||
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
||||
<div class="pjh-quick">
|
||||
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 작업 추가</span>로 할 일을 만듭니다.</div>
|
||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 업무 추가</span>로 할 일을 만듭니다.</div>
|
||||
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
||||
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
||||
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
||||
@@ -79,15 +79,15 @@
|
||||
<tr><th>용어</th><th>뜻</th></tr>
|
||||
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
||||
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
|
||||
<tr><td>작업</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 작업 하나입니다.</td></tr>
|
||||
<tr><td>세부 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
|
||||
<tr><td>담당자</td><td>그 작업을 책임지고 하는 사람 한 명입니다.</td></tr>
|
||||
<tr><td>협업자</td><td>작업의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
||||
<tr><td>업무</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 업무 하나입니다.</td></tr>
|
||||
<tr><td>세부 업무</td><td>업무를 더 잘게 나눈 할 일입니다. 업무 안에 목록으로 붙습니다. 원래 업무는 <b>상위 업무</b>라고 부릅니다.</td></tr>
|
||||
<tr><td>담당자</td><td>그 업무를 책임지고 하는 사람 한 명입니다.</td></tr>
|
||||
<tr><td>협업자</td><td>업무의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
||||
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
||||
<tr><td>우선순위</td><td>높음 · 보통 · 낮음. 급한 일을 표시합니다.</td></tr>
|
||||
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 작업이 쌓입니다.</td></tr>
|
||||
<tr><td>수신함</td><td>나를 태그한 작업과 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
||||
<tr><td>내 작업</td><td>모든 프로젝트에서 내가 담당자인 작업만 모아 보는 곳입니다.</td></tr>
|
||||
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 업무가 쌓입니다.</td></tr>
|
||||
<tr><td>수신함</td><td>나를 태그한 업무와 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
||||
<tr><td>내 업무</td><td>모든 프로젝트에서 내가 담당자인 업무만 모아 보는 곳입니다.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@@ -96,20 +96,20 @@
|
||||
<h2><span class="pjh-num">2</span>화면 구성</h2>
|
||||
<div class="pjh-map" aria-hidden="true">
|
||||
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>작업들</div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div>
|
||||
</div>
|
||||
<h3>왼쪽 사이드바</h3>
|
||||
<ul>
|
||||
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 작업을 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
||||
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 업무를 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
||||
<li><b>수신함</b> — 나를 태그한 업무와 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||
<li><b>내 업무</b> — 내가 담당자인 업무 모음. 숫자 배지는 아직 끝나지 않은 업무 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||
<li><b>휴지통</b> — 지운 업무를 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
||||
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
||||
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
||||
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 업무를 한눈에 봅니다.</li>
|
||||
</ul>
|
||||
<h3>위쪽 바</h3>
|
||||
<ul>
|
||||
@@ -134,8 +134,8 @@
|
||||
<h3>프로젝트</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||
<tr><td>프로젝트 보기, 작업·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>작업 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>프로젝트 보기, 업무·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>업무 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>섹션 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
|
||||
<tr><td>서브프로젝트 만들기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>새 프로젝트 만들기 (<span class="pjh-ui">+</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
@@ -146,13 +146,13 @@
|
||||
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
|
||||
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>전체 보기(모든 프로젝트 작업 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
|
||||
<tr><td>대시보드 “담당자별 작업 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
|
||||
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
|
||||
<tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
|
||||
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>수신함·내 작업·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
|
||||
<tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
|
||||
</table>
|
||||
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 작업은 원래 프로젝트 멤버가 아니면
|
||||
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고,
|
||||
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 업무는 원래 프로젝트 멤버가 아니면
|
||||
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 업무는 내 업무·수신함·알림·검색에서 사라지고,
|
||||
예전 링크로도 열리지 않습니다.</p>
|
||||
<h3>목표·주간 회의록</h3>
|
||||
<table class="pjh-table">
|
||||
@@ -166,7 +166,7 @@
|
||||
<tr><td>회의 완료·완료 해제(완료하면 수정 잠금)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>회의록 삭제</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>회의록 보드 열기·링크 복사</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>회의록 “작업 등록 표”로 작업 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
||||
<tr><td>회의록 “업무 등록 표”로 업무 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@@ -199,14 +199,14 @@
|
||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
||||
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
||||
<h3>프로젝트 삭제</h3>
|
||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 업무도 모두 함께 지워집니다.</p>
|
||||
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
||||
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
||||
<h3>멤버 배정 (Pro user 이상)</h3>
|
||||
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
||||
<ul>
|
||||
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
|
||||
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 작업 목록이 뜹니다.</li>
|
||||
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 업무 목록이 뜹니다.</li>
|
||||
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
@@ -215,7 +215,7 @@
|
||||
<section class="pjh-sec" id="views">
|
||||
<h2><span class="pjh-num">5</span>보기 전환과 필터</h2>
|
||||
<h3>보기 탭</h3>
|
||||
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 작업을 다른 모양으로 봅니다.</p>
|
||||
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 업무를 다른 모양으로 봅니다.</p>
|
||||
<table class="pjh-table">
|
||||
<tr><th>탭</th><th>이럴 때 좋아요</th></tr>
|
||||
<tr><td>보드</td><td>섹션(단계)별 카드로 흐름을 볼 때. 카드를 끌어 단계를 옮깁니다. (<a href="#board">6장</a>)</td></tr>
|
||||
@@ -225,12 +225,12 @@
|
||||
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
|
||||
</table>
|
||||
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 작업을 함께 봅니다
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
|
||||
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.
|
||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 작업</b>도 한 번씩 함께 보입니다.</p>
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
|
||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
|
||||
<h3>필터 바</h3>
|
||||
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||
<p>탭 아래 한 줄로 업무를 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||
<ul>
|
||||
<li><b>찾기</b> — 제목·설명·담당자에 들어간 글자로 거릅니다.</li>
|
||||
<li><b>상태</b> — 전체 / 미완료 / 완료</li>
|
||||
@@ -246,64 +246,64 @@
|
||||
|
||||
<!-- 6. 보드 -->
|
||||
<section class="pjh-sec" id="board">
|
||||
<h2><span class="pjh-num">6</span>보드 — 섹션과 작업 카드</h2>
|
||||
<h2><span class="pjh-num">6</span>보드 — 섹션과 업무 카드</h2>
|
||||
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
||||
<h3>섹션 다루기</h3>
|
||||
<ul>
|
||||
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·작업 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
||||
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·업무 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
||||
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
||||
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
||||
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
||||
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
||||
<ul>
|
||||
<li><span class="pjh-ui">메인 작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||
<li><span class="pjh-ui">메인 업무 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
||||
<li><span class="pjh-ui">섹션 작업 모두 완료</span> — 그 섹션의 미완료 작업을 한 번에 완료합니다.</li>
|
||||
<li><span class="pjh-ui">섹션 업무 모두 완료</span> — 그 섹션의 미완료 업무를 한 번에 완료합니다.</li>
|
||||
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
||||
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 작업은 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
||||
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 업무는 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||
<h3>작업 카드 다루기</h3>
|
||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 업무를 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||
<h3>업무 카드 다루기</h3>
|
||||
<ul>
|
||||
<li><b>상단 메인 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||
<li><b>하단 메인 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 작업은 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 작업은 상태만 표시합니다.</li>
|
||||
<li><b>상단 메인 업무 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 업무 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||
<li><b>하단 메인 업무 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 업무 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>업무 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 업무를 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||
<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> — <span class="pjh-ui">열기 · 작업 링크 복사 · 완료로 표시 · 삭제</span></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>
|
||||
<h3>마감일 색의 의미</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>표시</th><th>뜻</th></tr>
|
||||
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
|
||||
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 작업도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
|
||||
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
|
||||
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- 7. 카드의 세부 작업 -->
|
||||
<section class="pjh-sec" id="card-subtasks">
|
||||
<h2><span class="pjh-num">7</span>카드에서 세부 작업 다루기</h2>
|
||||
<p class="pjh-lead">세부 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 작업 목록이 펼쳐집니다.</p>
|
||||
<h2><span class="pjh-num">7</span>카드에서 세부 업무 다루기</h2>
|
||||
<p class="pjh-lead">세부 업무가 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 업무 목록이 펼쳐집니다.</p>
|
||||
<ul>
|
||||
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
||||
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
||||
<li><b>열기</b> — 줄을 누르면 그 세부 작업이 작업처럼 편집 창으로 열립니다.</li>
|
||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 세부 작업 삭제</span></li>
|
||||
<li><b>순서 바꾸기</b> — 펼친 세부 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||
<li><b>다른 작업으로 옮기기</b> — 세부 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 세부 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||
<li><b>열기</b> — 줄을 누르면 그 세부 업무가 업무처럼 편집 창으로 열립니다.</li>
|
||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 업무 열기 · 완료로 표시 · 세부 업무 삭제</span></li>
|
||||
<li><b>순서 바꾸기</b> — 펼친 세부 업무 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||
<li><b>다른 업무로 옮기기</b> — 세부 업무 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 업무의 세부 업무가 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||
</ul>
|
||||
<h3>+ 세부 작업 추가</h3>
|
||||
<h3>+ 세부 업무 추가</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 작업 추가</span>를 누릅니다.</li>
|
||||
<li>새 줄의 “작업 이름 입력” 칸에 이름을 씁니다.</li>
|
||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 업무 추가</span>를 누릅니다.</li>
|
||||
<li>새 줄의 “업무 이름 입력” 칸에 이름을 씁니다.</li>
|
||||
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 작업을 이어서 쓸 수 있습니다.</li>
|
||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 업무를 이어서 쓸 수 있습니다.</li>
|
||||
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
||||
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
||||
</ol>
|
||||
@@ -311,23 +311,23 @@
|
||||
|
||||
<!-- 8. 작업 편집 창 -->
|
||||
<section class="pjh-sec" id="task">
|
||||
<h2><span class="pjh-num">8</span>작업 편집 창</h2>
|
||||
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 작업 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
||||
<h2><span class="pjh-num">8</span>업무 편집 창</h2>
|
||||
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 업무 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
||||
<h3>맨 위 버튼</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>버튼</th><th>하는 일</th></tr>
|
||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 세부 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 업무의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 업무를 엽니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>업무를 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>업무를 지웁니다(만든 사람만). 세부 업무가 있으면 함께 지울지 한 번 더 묻습니다. 지운 업무는 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 업무를 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 업무는 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 업무 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||
<h3>제목과 기본 정보</h3>
|
||||
<ul>
|
||||
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
||||
<li><b>담당자</b> — 사진+이름을 누르면 “아이콘 + 이름” 목록에서 고릅니다. <span class="pjh-ui">담당자 없음</span>도 있습니다.</li>
|
||||
<li><b>섹션</b> — 이 작업이 들어갈 섹션을 고릅니다.</li>
|
||||
<li><b>섹션</b> — 이 업무가 들어갈 섹션을 고릅니다.</li>
|
||||
<li><b>우선순위</b> — 높음 · 보통 · 낮음</li>
|
||||
<li><b>마감일</b> — 달력 아이콘을 누르면 날짜 창이 열립니다. (<a href="#dates">10장</a>)</li>
|
||||
</ul>
|
||||
@@ -336,7 +336,7 @@
|
||||
<li>협업자는 사진+이름으로 보입니다. 사람에 마우스를 올리면 <span class="pjh-ui">×</span>가 나와 뺄 수 있습니다.</li>
|
||||
<li>협업자가 없으면 점선 원 <span class="pjh-ui">협업자 없음</span>을 눌러 추가하고, 있으면 옆 <span class="pjh-ui">+</span>로 추가합니다.</li>
|
||||
<li>오른쪽 <span class="pjh-ui">협업자로 참여</span> / <span class="pjh-ui">협업자에서 나가기</span>로 나 자신을 넣고 뺍니다.</li>
|
||||
<li>협업자에게는 작업 완료와 새 댓글 알림이 갑니다.</li>
|
||||
<li>협업자에게는 업무 완료와 새 댓글 알림이 갑니다.</li>
|
||||
</ul>
|
||||
<h3>설명</h3>
|
||||
<ul>
|
||||
@@ -344,39 +344,39 @@
|
||||
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
||||
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.</li>
|
||||
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 작업이 쌓입니다.</li>
|
||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 업무가 쌓입니다.</li>
|
||||
</ul>
|
||||
<h3>첨부 파일</h3>
|
||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
||||
<p>작업 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 작업을 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||
<p>업무 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 업무를 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
||||
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
||||
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
||||
</ol>
|
||||
<p>작업은 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 작업의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
||||
<p>업무는 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 업무의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
||||
<h3>댓글</h3>
|
||||
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
<p>업무 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 업무를 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 9. 작업 창의 세부 작업 -->
|
||||
<section class="pjh-sec" id="subtasks">
|
||||
<h2><span class="pjh-num">9</span>작업 창의 세부 작업</h2>
|
||||
<p class="pjh-lead">작업 편집 창 가운데 “세부 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||
<h2><span class="pjh-num">9</span>업무 창의 세부 업무</h2>
|
||||
<p class="pjh-lead">업무 편집 창 가운데 “세부 업무” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||
<ul>
|
||||
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
||||
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
||||
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
||||
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
||||
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 작업이 편집 창으로 열립니다.</li>
|
||||
<li><b>세부 작업의 세부 작업</b> — 그 세부 작업 안에도 세부 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 작업 삭제</span>.</li>
|
||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 업무가 편집 창으로 열립니다.</li>
|
||||
<li><b>세부 업무의 세부 업무</b> — 그 세부 업무 안에도 세부 업무가 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 업무 삭제</span>.</li>
|
||||
</ul>
|
||||
<h3>세부 작업을 열었을 때</h3>
|
||||
<p>세부 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 세부 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||
<h3>세부 업무를 열었을 때</h3>
|
||||
<p>세부 업무도 업무와 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 업무 이름</span>이 보이고, 누르면 상위 업무로 돌아갑니다. 세부 업무에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 10. 날짜 -->
|
||||
@@ -391,7 +391,7 @@
|
||||
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
||||
</ul>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div>보드 카드와 세부 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||
<div>보드 카드와 세부 업무 줄에서는 날짜를 누르는 즉시 저장됩니다. 업무 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||
</section>
|
||||
|
||||
<!-- 11. 목록 -->
|
||||
@@ -399,9 +399,9 @@
|
||||
<h2><span class="pjh-num">11</span>목록 보기</h2>
|
||||
<ul>
|
||||
<li><b>이 프로젝트</b> 범위에서는 섹션별로 묶여 보이고, <b>전체 프로젝트</b>에서는 프로젝트·섹션이 칸으로 나오는 표가 됩니다.</li>
|
||||
<li>칸 제목(작업 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
||||
<li>칸 제목(업무 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
||||
<li>칸 제목 사이 경계를 끌면 칸 너비가 바뀝니다.</li>
|
||||
<li>줄을 누르면 작업 편집 창, 우클릭하면 작업 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
||||
<li>줄을 누르면 업무 편집 창, 우클릭하면 업무 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -409,11 +409,11 @@
|
||||
<section class="pjh-sec" id="calendar">
|
||||
<h2><span class="pjh-num">12</span>캘린더 보기</h2>
|
||||
<ul>
|
||||
<li>한 달 달력에 작업이 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
||||
<li>한 달 달력에 업무가 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
||||
<li><span class="pjh-ui">‹</span> <span class="pjh-ui">›</span>로 지난달·다음 달로 갑니다.</li>
|
||||
<li>막대를 <b>누르면</b> 작업 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
||||
<li>하루에 작업이 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 작업 목록이 뜹니다.</li>
|
||||
<li>막대 우클릭 → 작업 메뉴(열기 · 작업 링크 복사 · 완료로 표시 · 삭제).</li>
|
||||
<li>막대를 <b>누르면</b> 업무 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
||||
<li>하루에 업무가 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 업무 목록이 뜹니다.</li>
|
||||
<li>막대 우클릭 → 업무 메뉴(열기 · 업무 링크 복사 · 완료로 표시 · 삭제).</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -421,14 +421,14 @@
|
||||
<section class="pjh-sec" id="timeline">
|
||||
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
||||
<ul>
|
||||
<li>기간이 있는(시작일 또는 마감일이 있는) 작업이 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
||||
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
|
||||
<li>카드에 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 작업은 작업 편집 창에서 봅니다.</li>
|
||||
<li>기간이 있는(시작일 또는 마감일이 있는) 업무가 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
||||
<li>업무는 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 업무는 기간만큼 막대로 늘어납니다.</li>
|
||||
<li>카드에 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 업무 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 업무는 업무 편집 창에서 봅니다.</li>
|
||||
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
|
||||
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 작업은 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
||||
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 업무는 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
||||
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
||||
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
||||
<li>카드의 <b>작업 이름을 누르면</b> 오른쪽에 작업 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 작업 메뉴. 마우스를 올리면 작업 정보가 보입니다.</li>
|
||||
<li>카드의 <b>업무 이름을 누르면</b> 오른쪽에 업무 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 업무 메뉴. 마우스를 올리면 업무 정보가 보입니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -436,24 +436,24 @@
|
||||
<section class="pjh-sec" id="dashboard">
|
||||
<h2><span class="pjh-num">14</span>대시보드</h2>
|
||||
<ul>
|
||||
<li>위쪽 숫자 카드 4개: <b>완료된 작업 합계 · 미완료 작업 합계 · 마감일이 지난 작업 합계 · 작업 합계</b></li>
|
||||
<li><b>미완료 작업 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
||||
<li><b>작업 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
||||
<li><b>담당자별 작업 합계(메인·세부 작업, 완료)</b> — 이 범위에서 사람별로 배정된 작업 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 작업·세부 작업 세로 막대</b>로 보여 줍니다(막대 하나 = 그 작업 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 작업 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 작업은 세부 작업에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
||||
<li>위쪽 숫자 카드 4개: <b>완료된 업무 합계 · 미완료 업무 합계 · 마감일이 지난 업무 합계 · 업무 합계</b></li>
|
||||
<li><b>미완료 업무 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
||||
<li><b>업무 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
||||
<li><b>담당자별 업무 합계(메인·세부 업무, 완료)</b> — 이 범위에서 사람별로 배정된 업무 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 업무·세부 업무 세로 막대</b>로 보여 줍니다(막대 하나 = 그 업무 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 업무 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 업무는 세부 업무에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
||||
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- 15. 내 작업 -->
|
||||
<section class="pjh-sec" id="mytasks">
|
||||
<h2><span class="pjh-num">15</span>내 작업</h2>
|
||||
<p class="pjh-lead">왼쪽 사이드바 <b>내 작업</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 작업만 한 표로 보여줍니다.</p>
|
||||
<h2><span class="pjh-num">15</span>내 업무</h2>
|
||||
<p class="pjh-lead">왼쪽 사이드바 <b>내 업무</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 업무만 한 표로 보여줍니다.</p>
|
||||
<ul>
|
||||
<li>위쪽 탭 <span class="pjh-ui">진행 중 · 완료 · 전체</span>로 고릅니다. 옆에 전체 개수와 지연(마감 지남) 개수가 나옵니다.</li>
|
||||
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
||||
<li>칸 제목을 누르면 정렬합니다.</li>
|
||||
<li>줄을 누르면 그 작업의 프로젝트 화면으로 가서 작업 편집 창이 바로 열립니다. 우클릭하면 작업 메뉴가 나옵니다.</li>
|
||||
<li>내가 담당자인 세부 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||
<li>줄을 누르면 그 업무의 프로젝트 화면으로 가서 업무 편집 창이 바로 열립니다. 우클릭하면 업무 메뉴가 나옵니다.</li>
|
||||
<li>내가 담당자인 세부 업무는 상위 업무 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -461,26 +461,26 @@
|
||||
<section class="pjh-sec" id="comments">
|
||||
<h2><span class="pjh-num">16</span>댓글과 @태그</h2>
|
||||
<h3>댓글 대화창</h3>
|
||||
<p>카드·목록·캘린더·내 작업에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
||||
<p>카드·목록·캘린더·내 업무에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
||||
<ul>
|
||||
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>. <kbd>Shift</kbd>+<kbd>Enter</kbd>로 줄바꿈합니다. 입력칸은 높이 70px로 고정되며 긴 글은 칸 안에서 스크롤됩니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 작업 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 업무 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
||||
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||
<li>아직 읽지 않은 새 댓글이 있으면 말풍선이 깜빡이고 숫자가 빨간색으로 바뀝니다.</li>
|
||||
</ul>
|
||||
<h3>반응 · 답글 · 완료 표시 (아사나식)</h3>
|
||||
<ul>
|
||||
<li><b>반응</b> — 댓글에 마우스를 올리면 오른쪽 위에 👍 👀 🙌 ✅ 와 <span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>가 뜹니다. 누르면 댓글 아래에 반응이 붙고(누른 사람 수), 내가 누른 반응은 파랗게 보입니다. 다시 누르면 취소됩니다. 반응에 마우스를 올리면 누가 눌렀는지 보입니다.</li>
|
||||
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 작업 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
||||
<li><b>작업 완료</b> — 작업을 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 작업을 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
||||
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 업무 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
||||
<li><b>업무 완료</b> — 업무를 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 업무를 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
||||
<li><b>@태그 표시</b> — 댓글 속 <kbd>@아이디</kbd>는 프로필 아이콘 + 이름 칩으로 보입니다.</li>
|
||||
</ul>
|
||||
<h3>@태그로 동료 부르기</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>설명이나 댓글에서 <kbd>@</kbd>를 누릅니다.</li>
|
||||
<li>이름 몇 글자를 치면 목록이 좁혀집니다. 방향키와 <kbd>Enter</kbd> 또는 마우스로 고릅니다.</li>
|
||||
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 작업</b>에 이 작업이 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
||||
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 업무</b>에 이 업무가 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
@@ -489,22 +489,22 @@
|
||||
<h2><span class="pjh-num">17</span>수신함과 알림</h2>
|
||||
<h3>수신함 화면</h3>
|
||||
<ul>
|
||||
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||
작업 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(작업 창을 직접 닫을 때와 같음).
|
||||
<li><b>나를 태그한 업무</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
||||
<li><b>알림</b> — 업무 배정 · 업무 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 업무 창</b>이 열리고(나를 태그한 업무도 같음), 업무 창이 열린 채 다른 줄을 누르면 업무 창이 그 업무로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 업무의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 업무가 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||
업무 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(업무 창을 직접 닫을 때와 같음).
|
||||
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
||||
다른 프로젝트에서 연결돼 와 읽기만 되는 작업의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||
다른 프로젝트에서 연결돼 와 읽기만 되는 업무의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||
</ul>
|
||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>알림</th><th>받는 사람</th></tr>
|
||||
<tr><td>작업 배정</td><td>새로 담당자가 된 사람</td></tr>
|
||||
<tr><td>작업 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
|
||||
<tr><td>업무 배정</td><td>새로 담당자가 된 사람</td></tr>
|
||||
<tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
|
||||
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
|
||||
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 작업”)</td></tr>
|
||||
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr>
|
||||
</table>
|
||||
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 작업 배정·완료는 관리자 메일로도 갑니다.</p>
|
||||
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 18. 검색과 공유 -->
|
||||
@@ -513,14 +513,14 @@
|
||||
<h3>전체 검색</h3>
|
||||
<ul>
|
||||
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(세부 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||
<li>결과를 누르면 그 작업이 열립니다.</li>
|
||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 업무(세부 업무 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||
<li>결과를 누르면 그 업무가 열립니다.</li>
|
||||
</ul>
|
||||
<h3>공유 링크</h3>
|
||||
<ul>
|
||||
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
|
||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 세부 작업 링크는 세부 작업 자체가 열립니다.</li>
|
||||
<li>현재 그 작업을 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||
<li>업무 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">업무 링크 복사</span>로 주소를 복사합니다.</li>
|
||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 업무가 바로 열립니다. 세부 업무 링크는 세부 업무 자체가 열립니다.</li>
|
||||
<li>현재 그 업무를 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -528,13 +528,13 @@
|
||||
<section class="pjh-sec" id="trash">
|
||||
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
|
||||
<ul>
|
||||
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 작업만 보입니다.</li>
|
||||
<li>지운 업무는 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 업무 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 업무 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 업무만 보입니다.</li>
|
||||
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
||||
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
||||
</ul>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div>세부 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
||||
<div>세부 업무만 따로 지웠는데 상위 업무도 지워진 상태라면, 상위 업무를 먼저 복구해야 합니다.</div></div>
|
||||
</section>
|
||||
|
||||
<!-- 20. 연간 목표 -->
|
||||
@@ -595,7 +595,7 @@
|
||||
</ol>
|
||||
|
||||
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
|
||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 업무를 멈춥니다.</p>
|
||||
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
||||
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||
</section>
|
||||
@@ -633,13 +633,15 @@
|
||||
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
||||
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||
|
||||
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 작업 등록</h3>
|
||||
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>작업 등록</b> 표입니다.</p>
|
||||
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 업무 등록</h3>
|
||||
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>업무 등록</b> 표입니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
<li><b>작업 등록</b> — 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다.</li>
|
||||
<li><b>업무 등록</b>(제목에 <b>N주차 업무 등록</b>) — 주차마다 한 표를 <b>모두가 같이</b> 봅니다(다른 사람이 적거나 등록한 줄도 보임, 30초마다·창을 다시 볼 때 새로 읽음). 내가 멤버가 아닌 프로젝트를 고른 남의 줄은 프로젝트 이름을 가립니다. 회의 완료면 읽기 전용입니다.
|
||||
<b>업무</b> 칸 — 비워 두면 고른 섹션에 새 업무로, 업무를 고르면 <b>그 업무의 세부 업무</b>로 등록합니다(목록 = 그 섹션의 진행 중인 메인 업무, 고르면 섹션 칸은 —). 등록된 줄의 <b>제목을 누르면 오른쪽에 업무 창</b>이 열려 바로 편집할 수 있습니다(업무 창에서 저장이 끝나야 닫히거나 다른 업무로 바뀝니다).
|
||||
<span class="pjh-ui">크게 열기</span> — 같은 표를 넓은 창으로 열어 씁니다(줄·저장은 그대로, <kbd>Esc</kbd>·×로 닫기). 제목 칸에 업무 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다(완료 프로젝트·완료 섹션은 목록에 나오지 않습니다). 목록 맨 위 <span class="pjh-ui">새 프로젝트</span>(Pro user 이상)·<span class="pjh-ui">새 섹션</span>(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 <span class="pjh-ui">새 섹션</span>을 만들어 고르세요.</li>
|
||||
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
|
||||
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 <b>등록됨</b> 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
||||
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 작업도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 작업 삭제는 만든 사람만 할 수 있습니다.</li>
|
||||
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 업무가 만들어지고, 줄 오른쪽에 <b>체크 표시</b>(누르면 새 탭에서 업무 열기)가 생기고, 제목을 누르면 오른쪽에 업무 창이 열립니다. 줄은 서버에 저장돼 같은 주차를 보는 모두에게 보입니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
||||
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 업무도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 업무 삭제는 만든 사람만 할 수 있습니다.</li>
|
||||
</ol>
|
||||
<table class="pjh-table">
|
||||
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
||||
@@ -697,11 +699,13 @@
|
||||
<ul>
|
||||
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
||||
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</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>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 업무에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
||||
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||
</section>
|
||||
@@ -712,20 +716,20 @@
|
||||
<h3>단축키</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>키</th><th>하는 일</th></tr>
|
||||
<tr><td><kbd>/</kbd></td><td>작업 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||
<tr><td><kbd>Enter</kbd></td><td>세부 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||
<tr><td><kbd>/</kbd></td><td>업무 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||
<tr><td><kbd>Esc</kbd></td><td>업무 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||
<tr><td><kbd>Enter</kbd></td><td>세부 업무 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
||||
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 세부 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||
<tr><td>마우스 오른쪽 버튼</td><td>업무 · 세부 업무 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||
</table>
|
||||
<h3>자주 묻는 질문</h3>
|
||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 작업은 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 업무는 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||
<p><b>Q. 업무를 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||
<p><b>Q. 세부 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>세부 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||
<p><b>Q. 세부 업무를 다른 프로젝트 업무로 옮길 수 있나요?</b><br>세부 업무는 같은 프로젝트 안의 업무로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 업무를 두 프로젝트에 같이 두고 싶어요.</b><br>업무 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
||||
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -32,18 +32,18 @@
|
||||
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
|
||||
<div class="pj-inbox-section">
|
||||
<h3 class="pj-inbox-h3">
|
||||
나를 태그한 작업
|
||||
나를 태그한 업무
|
||||
<span class="pj-inbox-count" id="pj-mention-unread"
|
||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||
</h3>
|
||||
{% if not mentioned_tasks %}
|
||||
<div class="pj-empty">태그된 작업이 없습니다.</div>
|
||||
<div class="pj-empty">태그된 업무가 없습니다.</div>
|
||||
{% else %}
|
||||
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
||||
{% for t in mentioned_tasks %}
|
||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
||||
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 작업 창">
|
||||
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 업무 창">
|
||||
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
||||
<div class="pj-inbox-body">
|
||||
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
||||
@@ -76,6 +76,7 @@
|
||||
{% elif n.type == 'completed' %}task_alt
|
||||
{% elif n.type == 'comment' %}chat_bubble
|
||||
{% elif n.type == 'mention' %}alternate_email
|
||||
{% elif n.type == 'reaction' %}add_reaction
|
||||
{% elif n.type == 'due_soon' %}schedule
|
||||
{% elif n.type == 'due_today' %}today
|
||||
{% elif n.type == 'overdue' %}alarm
|
||||
@@ -101,5 +102,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
</div>
|
||||
<div class="pj-title-wrap">
|
||||
<h1 class="pj-project-title">
|
||||
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 작업</span>
|
||||
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 업무</span>
|
||||
</h1>
|
||||
</div>
|
||||
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
||||
@@ -40,7 +40,7 @@
|
||||
<div class="pj-filterbar" id="pj-mt-filterbar">
|
||||
<label class="pj-fb-search">
|
||||
<span class="material-symbols-outlined">filter_list</span>
|
||||
<input type="search" id="pj-mt-q" placeholder="내 작업에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
||||
<input type="search" id="pj-mt-q" placeholder="내 업무에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
||||
</label>
|
||||
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
||||
<option value="all">마감: 전체</option>
|
||||
@@ -62,7 +62,7 @@
|
||||
<thead></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 작업이 없습니다.</div>
|
||||
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 업무가 없습니다.</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<h3>이 PC 를 내 알림에 연결할까요?</h3>
|
||||
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
|
||||
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
|
||||
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
|
||||
<b>{{ user.name or user.email }}</b> 님의 태그·업무 배정 알림이 뜹니다.</p>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
|
||||
{% elif link %}
|
||||
<h3>이미 연결을 승인했습니다</h3>
|
||||
@@ -48,8 +48,8 @@
|
||||
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
|
||||
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
|
||||
</ol>
|
||||
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
||||
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
|
||||
<p class="pj-notifier-note">나를 태그하거나 업무가 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
||||
[열기]를 누르면 브라우저에서 그 업무가 열립니다.</p>
|
||||
</div>
|
||||
|
||||
<div class="pj-notifier-card">
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -191,7 +191,7 @@
|
||||
<div class="pj-view" data-view="list" hidden>
|
||||
<table class="pj-table" id="pj-list">
|
||||
<thead>
|
||||
<tr><th>작업</th><th>담당자</th><th>섹션</th><th>우선순위</th><th>시작</th><th>마감</th></tr>
|
||||
<tr><th>업무</th><th>담당자</th><th>섹션</th><th>우선순위</th><th>시작</th><th>마감</th></tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
@@ -216,7 +216,7 @@
|
||||
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
||||
<div class="pj-field-label">기본 담당자
|
||||
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
||||
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 작업을 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 작업만 이 사람에게 자동 배정됩니다.</span>
|
||||
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 업무를 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 업무만 이 사람에게 자동 배정됩니다.</span>
|
||||
</div>
|
||||
<div class="pj-modal-actions">
|
||||
<span style="flex:1"></span>
|
||||
@@ -237,13 +237,13 @@
|
||||
<div class="pj-modal-actions pj-modal-actions-top">
|
||||
<!-- 공유 — 이 업무의 퍼머링크(/project/t/{id})를 클립보드에 복사.
|
||||
받은 사람이 열면 로그인 후 이 업무 팝업이 바로 뜬다(멤버만). -->
|
||||
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 작업 링크 복사">
|
||||
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 업무 링크 복사">
|
||||
<span class="material-symbols-outlined">link</span> 공유
|
||||
</button>
|
||||
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
||||
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
||||
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
||||
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 작업이 있는 프로젝트 화면으로 이동">
|
||||
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 업무가 있는 프로젝트 화면으로 이동">
|
||||
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
||||
</button>
|
||||
<span style="flex:1"></span>
|
||||
@@ -258,15 +258,15 @@
|
||||
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
||||
<input type="hidden" id="pj-t-id" />
|
||||
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
||||
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 작업 열기">
|
||||
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 업무 열기">
|
||||
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
||||
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
||||
</button>
|
||||
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="작업 제목"></textarea>
|
||||
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="업무 제목"></textarea>
|
||||
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
||||
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
||||
<span class="material-symbols-outlined">visibility</span>
|
||||
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 작업이라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
||||
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 업무라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
||||
</div>
|
||||
|
||||
<div class="pj-modal-body">
|
||||
@@ -349,27 +349,7 @@
|
||||
<span class="pj-extra-label">설명</span>
|
||||
<span class="pj-muted-sm" id="pj-desc-hint"></span>
|
||||
</div>
|
||||
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
||||
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
||||
<div class="pj-desc-fmtbar" id="pj-desc-fmtbar">
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
||||
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<label class="pj-desc-fmtbtn" id="pj-desc-imgbtn" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="pj-desc-img-input" accept="image/*" hidden /></label>
|
||||
</div>
|
||||
{% include "project/_desc_fmtbar.html" %}
|
||||
<div class="pj-desc-wrap">
|
||||
<div class="pj-desc-editor" id="pj-t-desc" contenteditable="true" data-placeholder="설명을 입력하세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||
</div>
|
||||
@@ -379,13 +359,15 @@
|
||||
기존 업무 편집 시에만. -->
|
||||
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
||||
<div class="pj-extra-head">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 작업
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 업무
|
||||
</div>
|
||||
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
||||
<div class="pj-subtask-form">
|
||||
<input type="text" id="pj-subtask-input" placeholder="세부 작업 제목…" autocomplete="off" />
|
||||
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
||||
<input type="text" id="pj-subtask-input" placeholder="세부 업무 제목…" autocomplete="off" />
|
||||
{# 아이콘 순서는 보드 카드 새 줄과 같게 — 마감일 · 담당자 · 협업자 #}
|
||||
<input type="date" id="pj-subtask-add-due" />
|
||||
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
||||
<button type="button" class="pj-assignee-btn is-empty pj-subtask-add-fol" id="pj-subtask-add-followers" title="협업자 지정">협업자 없음</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -488,5 +470,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<section class="pj-main">
|
||||
<div class="pj-section-head">
|
||||
<h2>휴지통</h2>
|
||||
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
||||
<span class="pj-trash-note">삭제한 업무는 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
||||
</div>
|
||||
<div class="pj-view pj-inbox-pane">
|
||||
{% if not trash_enabled %}
|
||||
@@ -30,7 +30,7 @@
|
||||
<table class="pj-table pj-trash-table" id="pj-trash-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>작업</th>
|
||||
<th>업무</th>
|
||||
<th>프로젝트</th>
|
||||
<th>포함</th>
|
||||
<th>삭제한 사람</th>
|
||||
@@ -45,7 +45,7 @@
|
||||
<td class="pj-trash-title">{{ it.title }}</td>
|
||||
<td>{{ it.project_name or '-' }}</td>
|
||||
<td class="pj-trash-meta">
|
||||
{% if it.task_count > 1 %}세부 작업 {{ it.task_count - 1 }}{% endif %}
|
||||
{% if it.task_count > 1 %}세부 업무 {{ it.task_count - 1 }}{% endif %}
|
||||
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
||||
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
||||
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
+15
-1
@@ -1325,12 +1325,17 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
}
|
||||
.cpg-boxno-count.is-on { color: #217346; font-weight: 700; }
|
||||
.cpg-boxno-table { table-layout: fixed; width: 100%; }
|
||||
/* 출고 상세 상자 목록 — 위 요약 카드와 20px 띄움 */
|
||||
.cpg-calc-sum .cpg-boxno-scroll { margin-top: 20px; }
|
||||
/* 표 오른쪽 끝 = 요약 카드 오른쪽 끝 — 스크롤바 칸(10px)+여백(2px)을 카드 안쪽 여백(16px)으로 내보낸다 */
|
||||
.cpg-calc-sum .cpg-boxno-scroll { margin-right: -12px; }
|
||||
.cpg-boxno-table th, .cpg-boxno-table td {
|
||||
box-sizing: border-box;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
border-bottom: 1px solid var(--color-cloud-gray);
|
||||
text-align: center; /* 표 안 모든 칸 가운데 정렬 */
|
||||
}
|
||||
.cpg-boxno-table thead th {
|
||||
position: sticky; top: 0; z-index: 2;
|
||||
@@ -1348,7 +1353,7 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
.cpg-boxno-c-weight { width: 92px; }
|
||||
/* 상자 무게 합계(g) — 상자 단위 한 칸(rowspan), 오른쪽 정렬 숫자. 무게 없는 제품이 있으면 작은 표시 */
|
||||
.cpg-boxno-weight {
|
||||
text-align: right; vertical-align: middle; font-variant-numeric: tabular-nums; font-weight: 600;
|
||||
text-align: center; vertical-align: middle; font-variant-numeric: tabular-nums; font-weight: 600;
|
||||
border-left: 1px solid var(--color-cloud-gray);
|
||||
}
|
||||
.cpg-boxno-weight .cpg-weight-unit { font-weight: 400; }
|
||||
@@ -1362,6 +1367,14 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
vertical-align: middle;
|
||||
}
|
||||
.cpg-boxno-code { color: var(--color-midtone-gray); font-family: var(--font-geist-mono); }
|
||||
/* 합계 행 — 수량·무게(kg) 합계. 클릭 체크 대상 아님 */
|
||||
.cpg-boxno-table tfoot td {
|
||||
background: var(--color-ghost-gray);
|
||||
font-weight: 700;
|
||||
border-top: 1px solid var(--color-subtle-ash);
|
||||
border-bottom: 0;
|
||||
}
|
||||
.cpg-boxno-table tfoot .cpg-boxno-cell { font-family: inherit; }
|
||||
.cpg-boxno-table tbody tr.is-boxtop td { border-top: 1px solid var(--color-cloud-gray); }
|
||||
.cpg-boxno-table tbody tr { cursor: pointer; }
|
||||
.cpg-boxno-table tbody tr:hover td { background: var(--color-ghost-gray); }
|
||||
@@ -1485,6 +1498,7 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
}
|
||||
.cpg-calc-sum .cpg-boxno-scroll { margin-right: 0; padding-right: 0; } /* 스크롤 없음 — 스크롤바 칸도 없다 */
|
||||
}
|
||||
|
||||
/* ── 넓은 화면(3열): ③ 카드 자체가 스크롤러 ──
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// 긴급 공지 관리(/notice/, 수퍼관리자) — 만들기·고치기·취소·미리 보기·확인 현황.
|
||||
// 내용 편집기·날짜 팝업·받는 사람 고르기는 프로젝트 화면 부품 그대로(window.PJLib — project.js, PJ_LIB_ONLY):
|
||||
// · 내용 = 작업 설명란과 같은 편집기(굵게·기울임·밑줄·취소선·글자 색/크기·목록·체크리스트·인용·링크·서식 지우기·이미지
|
||||
// 붙여넣기/버튼·크기 조절), 이미지는 /notice/api/images 로 올린다.
|
||||
// · 띄울 날짜 = 아사나식 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸.
|
||||
// · 받는 사람 = 프로젝트 멤버 고르기와 같은 아이콘 + 이름 + 체크.
|
||||
(function () {
|
||||
"use strict";
|
||||
const root = document.getElementById("ntc-root");
|
||||
if (!root || !window.PJLib) return;
|
||||
const L = window.PJLib;
|
||||
const $ = function (id) { return document.getElementById(id); };
|
||||
const people = window.NTC_PEOPLE || [];
|
||||
const byEmail = {};
|
||||
people.forEach(function (p) { byEmail[String(p.email).toLowerCase()] = p; });
|
||||
const nameOf = function (e) { const p = byEmail[String(e).toLowerCase()]; return p ? p.name : String(e).split("@")[0]; };
|
||||
const esc = function (s) {
|
||||
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||
});
|
||||
};
|
||||
const shortWhen = function (iso) {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || "");
|
||||
return m ? m[1] + "-" + m[2] + "-" + m[3] + " " + m[4] + ":" + m[5] : "";
|
||||
};
|
||||
async function api(method, url, body, isForm) {
|
||||
const opts = { method: method, credentials: "same-origin", headers: {} };
|
||||
if (body !== undefined) {
|
||||
if (isForm) opts.body = body;
|
||||
else { opts.headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(body); }
|
||||
}
|
||||
const res = await fetch(url, opts);
|
||||
let data = null;
|
||||
try { data = await res.json(); } catch (_) {}
|
||||
if (!res.ok) {
|
||||
const d = data && data.detail;
|
||||
throw new Error(typeof d === "string" ? d : "HTTP " + res.status);
|
||||
}
|
||||
return data || {};
|
||||
}
|
||||
|
||||
const title = $("ntc-title"), dateEl = $("ntc-date"), timeEl = $("ntc-time"), idEl = $("ntc-id");
|
||||
const peopleBox = $("ntc-people"), msg = $("ntc-msg"), save = $("ntc-save");
|
||||
const say = function (text, ok) { msg.textContent = text || ""; msg.hidden = !text; msg.classList.toggle("is-ok", !!ok); };
|
||||
|
||||
// ── 내용 — 작업 설명란 편집기 ──
|
||||
const editor = L.createDescEditor({
|
||||
box: $("ntc-body"), fmtbar: $("ntc-fmtbar"), imgInput: $("ntc-img-input"), hint: $("ntc-hint"), mentions: false,
|
||||
uploadImage: async function (file) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file, file.name || "image");
|
||||
return (await api("POST", "/notice/api/images", fd, true)).image.url;
|
||||
},
|
||||
});
|
||||
// ── 날짜 — 프로젝트 날짜 팝업 ──
|
||||
L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" });
|
||||
// ── 받는 사람 — 프로젝트 멤버 고르기 모양 ──
|
||||
peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>';
|
||||
function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; }
|
||||
root.querySelectorAll('input[name="ntc-to"]').forEach(function (r) {
|
||||
r.addEventListener("change", function () { peopleBox.hidden = toAll(); });
|
||||
});
|
||||
function picked() {
|
||||
return Array.from(peopleBox.querySelectorAll("input[type=checkbox]:checked")).map(function (c) { return c.value; });
|
||||
}
|
||||
function setPicked(emails) {
|
||||
const want = (emails || []).map(function (e) { return String(e).toLowerCase(); });
|
||||
peopleBox.querySelectorAll("input[type=checkbox]").forEach(function (c) { c.checked = want.indexOf(c.value.toLowerCase()) >= 0; });
|
||||
}
|
||||
|
||||
// ── 저장(만들기·고치기) ──
|
||||
function showAtValue() {
|
||||
// 날짜를 비우면 바로(서버가 지금으로), 날짜만 있으면 그날 00:00, 시각까지 있으면 그 시각 — 모두 한국시간
|
||||
return dateEl.value ? dateEl.value + "T" + (timeEl.value || "00:00") : "";
|
||||
}
|
||||
function payload() {
|
||||
return {
|
||||
title: title.value.trim(), body_html: editor.getHtml(), show_at: showAtValue(),
|
||||
to_all: toAll(), targets: picked(), reshow: $("ntc-reshow").checked,
|
||||
};
|
||||
}
|
||||
function resetForm() {
|
||||
idEl.value = ""; title.value = ""; editor.setHtml(""); dateEl.value = ""; timeEl.value = "";
|
||||
root.querySelector('input[name="ntc-to"][value="all"]').checked = true;
|
||||
peopleBox.hidden = true;
|
||||
setPicked([]);
|
||||
$("ntc-reshow").checked = false; $("ntc-reshow-row").hidden = true;
|
||||
$("ntc-form-title").textContent = "새 긴급 공지";
|
||||
save.textContent = "공지 만들기";
|
||||
}
|
||||
$("ntc-reset").addEventListener("click", function () { resetForm(); say(""); });
|
||||
let saving = false;
|
||||
save.addEventListener("click", async function () {
|
||||
if (saving) return;
|
||||
saving = true; save.disabled = true;
|
||||
try {
|
||||
await editor.whenIdle(); // 이미지 올리는 중이면 끝난 뒤 저장(빠진 채 저장되지 않게)
|
||||
const p = payload();
|
||||
if (!p.title) { say("제목을 입력하세요."); title.focus(); return; }
|
||||
if (!p.to_all && !p.targets.length) { say("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요."); return; }
|
||||
const id = idEl.value;
|
||||
if (id) await api("PUT", "/notice/api/notices/" + id, p);
|
||||
else await api("POST", "/notice/api/notices", p);
|
||||
resetForm();
|
||||
say(id ? "공지를 고쳤습니다." : "공지를 만들었습니다. 띄울 시각이 되면 받는 사람 화면 가운데에 나타납니다.", true);
|
||||
await loadList();
|
||||
} catch (e) { say("저장하지 못했습니다: " + e.message); }
|
||||
finally { saving = false; save.disabled = false; }
|
||||
});
|
||||
|
||||
// ── 미리 보기 — 받는 사람 화면과 같은 모양 ──
|
||||
$("ntc-preview").addEventListener("click", function () { preview(title.value.trim() || "(제목 없음)", editor.getHtml()); });
|
||||
function preview(t, html) {
|
||||
const box = document.createElement("div");
|
||||
box.className = "erp-notice-backdrop";
|
||||
box.innerHTML = '<div class="erp-notice-card" role="dialog" aria-modal="true">' +
|
||||
'<div class="erp-notice-head"><span class="erp-notice-badge">긴급 공지 · 미리 보기</span></div>' +
|
||||
'<h2 class="erp-notice-title"></h2><div class="erp-notice-body"></div>' +
|
||||
'<div class="erp-notice-foot"><span class="erp-notice-meta">받는 사람 화면에는 [확인]만 있습니다</span>' +
|
||||
'<button type="button" class="erp-notice-ok">닫기</button></div></div>';
|
||||
box.querySelector(".erp-notice-title").textContent = t;
|
||||
box.querySelector(".erp-notice-body").innerHTML = html; // 저장하면 서버가 다시 정리한다
|
||||
document.body.appendChild(box);
|
||||
const ok = box.querySelector(".erp-notice-ok");
|
||||
ok.addEventListener("click", function () { box.remove(); });
|
||||
box.addEventListener("keydown", function (e) { if (e.key === "Escape") box.remove(); });
|
||||
ok.focus();
|
||||
}
|
||||
|
||||
// ── 목록 ──
|
||||
let list = [];
|
||||
function stateOf(n) {
|
||||
if (n.cancelled_at) return ["is-cancelled", "취소됨"];
|
||||
if (new Date(n.show_at) > new Date()) return ["is-scheduled", "예약 " + shortWhen(n.show_at)];
|
||||
return ["is-live", "표시 중"];
|
||||
}
|
||||
function render() {
|
||||
const box = $("ntc-list");
|
||||
if (!list.length) { box.textContent = "아직 공지가 없습니다."; return; }
|
||||
box.innerHTML = list.map(function (n) {
|
||||
const st = stateOf(n);
|
||||
const acked = Object.keys(n.acks || {});
|
||||
const who = n.to_all ? "전체" : n.targets.map(nameOf).join(", ");
|
||||
const ackLine = n.to_all ? "확인 " + acked.length + "명"
|
||||
: "확인 " + n.targets.filter(function (e) { return n.acks[e]; }).length + " / " + n.targets.length + "명";
|
||||
const rows = (n.to_all ? acked : n.targets).map(function (e) {
|
||||
return n.acks[e] ? "<li>" + esc(nameOf(e)) + " — " + esc(shortWhen(n.acks[e])) + "</li>"
|
||||
: '<li class="is-no">' + esc(nameOf(e)) + " — 아직 확인 안 함</li>";
|
||||
}).join("");
|
||||
return '<div class="ntc-item" data-id="' + n.id + '">' +
|
||||
'<div class="ntc-item-head"><span class="ntc-state ' + st[0] + '">' + esc(st[1]) + "</span>" +
|
||||
'<span class="ntc-item-title">' + esc(n.title) + "</span>" +
|
||||
'<span class="ntc-item-acts">' +
|
||||
'<button type="button" class="pj-btn pj-btn-sm" data-act="preview">미리 보기</button>' +
|
||||
'<button type="button" class="pj-btn pj-btn-sm" data-act="edit">고치기</button>' +
|
||||
'<button type="button" class="pj-btn pj-btn-sm" data-act="cancel">' + (n.cancelled_at ? "취소 되돌리기" : "취소") + "</button>" +
|
||||
"</span></div>" +
|
||||
'<div class="ntc-item-meta">띄울 시각 ' + esc(shortWhen(n.show_at)) + " · 받는 사람 " + esc(who) +
|
||||
" · 만든 사람 " + esc(nameOf(n.created_by)) + "</div>" +
|
||||
'<details class="ntc-acks"><summary>' + esc(ackLine) + "</summary><ul>" + (rows || "<li>아직 없습니다</li>") + "</ul></details>" +
|
||||
"</div>";
|
||||
}).join("");
|
||||
}
|
||||
async function loadList() {
|
||||
try { list = (await api("GET", "/notice/api/notices")).notices || []; render(); }
|
||||
catch (e) { $("ntc-list").textContent = "목록을 읽지 못했습니다: " + e.message; }
|
||||
}
|
||||
$("ntc-list").addEventListener("click", async function (e) {
|
||||
const b = e.target.closest("[data-act]");
|
||||
if (!b) return;
|
||||
const n = list.find(function (x) { return String(x.id) === b.closest(".ntc-item").dataset.id; });
|
||||
if (!n) return;
|
||||
if (b.dataset.act === "preview") { preview(n.title, n.body_html); return; }
|
||||
if (b.dataset.act === "edit") {
|
||||
idEl.value = n.id; title.value = n.title; editor.setHtml(n.body_html);
|
||||
dateEl.value = (n.show_at || "").slice(0, 10); timeEl.value = (n.show_at || "").slice(11, 16);
|
||||
root.querySelector('input[name="ntc-to"][value="' + (n.to_all ? "all" : "some") + '"]').checked = true;
|
||||
peopleBox.hidden = n.to_all;
|
||||
setPicked(n.targets);
|
||||
$("ntc-reshow-row").hidden = false; $("ntc-reshow").checked = false;
|
||||
$("ntc-form-title").textContent = "공지 고치기";
|
||||
save.textContent = "고친 내용 저장";
|
||||
say("");
|
||||
title.focus();
|
||||
return;
|
||||
}
|
||||
if (b.dataset.act === "cancel") {
|
||||
const cancel = !n.cancelled_at;
|
||||
if (cancel) {
|
||||
const q = "'" + n.title + "' 공지를 취소할까요? 아직 확인하지 않은 사람에게도 더 뜨지 않습니다.";
|
||||
const yes = window.erpConfirm ? await window.erpConfirm(q, { okText: "공지 취소", cancelText: "닫기" }) : window.confirm(q);
|
||||
if (!yes) return;
|
||||
}
|
||||
b.disabled = true;
|
||||
try { await api("POST", "/notice/api/notices/" + n.id + "/cancel", { cancel: cancel }); await loadList(); }
|
||||
catch (err) { say("처리하지 못했습니다: " + err.message); b.disabled = false; }
|
||||
}
|
||||
});
|
||||
loadList();
|
||||
})();
|
||||
@@ -0,0 +1,97 @@
|
||||
/* 긴급 공지 — 화면 가로·세로 정가운데(erp-notice.js). 화면 배율(.erp-app zoom) 밖 body 에 붙는다. */
|
||||
.erp-notice-backdrop {
|
||||
position: fixed; inset: 0; z-index: 6000;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
padding: 16px; box-sizing: border-box;
|
||||
background: rgba(15, 17, 21, .5);
|
||||
}
|
||||
.erp-notice-backdrop[hidden] { display: none; }
|
||||
.erp-notice-card {
|
||||
width: min(640px, 100%); max-height: min(86vh, 900px); box-sizing: border-box;
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
padding: 22px 24px 18px; border-radius: 14px; background: #fff; color: #1e1f21;
|
||||
box-shadow: 0 18px 50px rgba(0, 0, 0, .35); border-top: 6px solid #e5484d;
|
||||
animation: erp-notice-in .18s ease-out;
|
||||
}
|
||||
@keyframes erp-notice-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
|
||||
.erp-notice-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.erp-notice-badge {
|
||||
display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 999px;
|
||||
background: #fde8e8; color: #c62a2f; font-size: 12.5px; font-weight: 800;
|
||||
}
|
||||
.erp-notice-count { font-size: 12.5px; font-weight: 700; color: #6b7079; }
|
||||
.erp-notice-title { margin: 0; font-size: 20px; font-weight: 800; line-height: 1.35; word-break: keep-all; overflow-wrap: anywhere; }
|
||||
.erp-notice-body {
|
||||
flex: 1 1 auto; min-height: 0; overflow: auto; font-size: 14.5px; line-height: 1.65; color: #2b2f36;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.erp-notice-body p { margin: 0 0 .6em; }
|
||||
.erp-notice-body img { display: block; max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px; }
|
||||
.erp-notice-body a { color: #3b6fd8; text-decoration: underline; }
|
||||
/* 작업 설명란 편집기와 같은 서식(project.css .pj-desc-editor) — 프로젝트 밖 화면에서도 같게 보이게 */
|
||||
.erp-notice-body blockquote { margin: 6px 0; padding: 2px 12px; border-left: 3px solid #d5d9de; color: #565c66; }
|
||||
.erp-notice-body ul, .erp-notice-body ol { margin: 4px 0; padding-left: 22px; }
|
||||
.erp-notice-body ul.pj-checklist { list-style: none; padding-left: 24px; }
|
||||
.erp-notice-body ul.pj-checklist > li { position: relative; }
|
||||
.erp-notice-body ul.pj-checklist > li::before {
|
||||
content: ""; position: absolute; left: -22px; top: .3em; width: 14px; height: 14px;
|
||||
box-sizing: border-box; border: 1.5px solid #8f959d; border-radius: 3px; background: #fff;
|
||||
}
|
||||
.erp-notice-body ul.pj-checklist > li[data-checked="true"]::before {
|
||||
border-color: #7b68ee; background: #7b68ee center / 10px 10px no-repeat
|
||||
url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2 6.3l2.6 2.6L10 3.4' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
|
||||
}
|
||||
.erp-notice-body ul.pj-checklist > li[data-checked="true"] { color: #9aa1a9; text-decoration: line-through; }
|
||||
.erp-notice-body img[width] { height: auto; }
|
||||
.erp-notice-error { margin: 0; padding: 6px 10px; border-radius: 6px; background: #fdecec; color: #b42318; font-size: 13px; }
|
||||
.erp-notice-error[hidden] { display: none; }
|
||||
.erp-notice-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 6px; border-top: 1px solid #eceef1; }
|
||||
.erp-notice-meta { font-size: 12.5px; color: #6b7079; }
|
||||
.erp-notice-ok {
|
||||
min-width: 96px; padding: 9px 20px; border: none; border-radius: 8px; cursor: pointer;
|
||||
background: #e5484d; color: #fff; font-size: 14.5px; font-weight: 800;
|
||||
}
|
||||
.erp-notice-ok:hover { background: #d23c41; }
|
||||
.erp-notice-ok:focus-visible { outline: 3px solid rgba(229, 72, 77, .35); outline-offset: 2px; }
|
||||
.erp-notice-ok:disabled { opacity: .6; cursor: default; }
|
||||
|
||||
/* 관리 화면(/notice/) */
|
||||
.ntc-wrap { display: grid; grid-template-columns: minmax(420px, 640px) 1fr; gap: 18px; align-items: start; }
|
||||
@media (max-width: 1100px) { .ntc-wrap { grid-template-columns: 1fr; } }
|
||||
.ntc-card { background: #fff; border: 1px solid #e6e8eb; border-radius: 12px; padding: 18px; }
|
||||
.ntc-card h2 { margin: 0 0 12px; font-size: 16px; }
|
||||
.ntc-field { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; font-size: 13px; font-weight: 700; color: #3b4048; }
|
||||
.ntc-field input[type=text], .ntc-time {
|
||||
font: inherit; font-weight: 500; padding: 8px 10px; border: 1px solid #d5d9de; border-radius: 8px;
|
||||
}
|
||||
.ntc-sub { font-weight: 500; color: #8a9099; }
|
||||
.ntc-desc .pj-desc-toolbar { display: flex; align-items: center; gap: 8px; }
|
||||
.ntc-desc .pj-desc-wrap { position: relative; }
|
||||
.ntc-desc .pj-desc-editor { min-height: 180px; max-height: 460px; overflow: auto; font-weight: 400;
|
||||
padding: 10px 12px; border: 1px solid #d5d9de; border-radius: 8px; }
|
||||
.ntc-desc .pj-desc-editor:focus { border-color: #7b68ee; box-shadow: 0 0 0 3px rgba(123, 104, 238, .15); outline: none; }
|
||||
.ntc-when { display: flex; align-items: center; gap: 8px; font-weight: 500; }
|
||||
.ntc-time { padding: 6px 8px; }
|
||||
.ntc-targets { display: flex; flex-direction: column; gap: 8px; font-weight: 500; }
|
||||
.ntc-to { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
.ntc-people { max-height: 260px; }
|
||||
.ntc-people[hidden] { display: none; }
|
||||
.ntc-inline { flex-direction: row; align-items: center; font-weight: 500; }
|
||||
.ntc-actions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
||||
.ntc-msg { margin: 8px 0 0; font-size: 13px; color: #b42318; }
|
||||
.ntc-msg[hidden] { display: none; }
|
||||
.ntc-msg.is-ok { color: #1f7a3a; }
|
||||
.ntc-list { display: flex; flex-direction: column; gap: 10px; }
|
||||
.ntc-item { border: 1px solid #e6e8eb; border-radius: 10px; padding: 12px 14px; }
|
||||
.ntc-item-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.ntc-item-title { font-weight: 800; font-size: 14.5px; }
|
||||
.ntc-state { padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 800; }
|
||||
.ntc-state.is-live { background: #fde8e8; color: #c62a2f; }
|
||||
.ntc-state.is-scheduled { background: #e8efff; color: #3456b8; }
|
||||
.ntc-state.is-cancelled { background: #eef0f2; color: #6b7079; }
|
||||
.ntc-item-meta { margin-top: 4px; font-size: 12.5px; color: #6b7079; }
|
||||
.ntc-item-acts { margin-left: auto; display: flex; gap: 6px; }
|
||||
.ntc-acks { margin-top: 8px; font-size: 12.5px; color: #3b4048; }
|
||||
.ntc-acks summary { cursor: pointer; font-weight: 700; }
|
||||
.ntc-acks ul { margin: 6px 0 0; padding-left: 18px; }
|
||||
.ntc-acks .is-no { color: #b42318; }
|
||||
@@ -0,0 +1,118 @@
|
||||
// 긴급 공지 — ERP 모든 화면(erp_base.html) 가운데에 띄운다(2026-10-12).
|
||||
// · GET /notice/api/pending — 띄울 시각이 지났고 아직 [확인] 안 한 내 공지(오래된 것부터). 30초마다·창을 다시 볼 때.
|
||||
// · [확인]을 누를 때까지 닫히지 않는다(Esc·바깥 클릭으로 안 닫힘). 여러 건이면 차례대로(1/3).
|
||||
// · [확인] = POST /notice/api/{id}/ack — 실패하면 창을 그대로 두고 알린다. 다른 탭에서 확인하면 이 탭도 다음 확인 때 닫힌다.
|
||||
// · 본문 HTML 은 서버가 정리한 것(이미지는 /notice/images/{id} 만). 수신함 오른쪽 작업 창(iframe) 안에서는 돌지 않는다.
|
||||
// · 024 미적용(503)·로그아웃(401)이면 조용히 멈춘다.
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.top !== window) return; // iframe(수신함 작업 창 등) 안에서는 바깥 화면이 띄운다
|
||||
const POLL_MS = 30000;
|
||||
let queue = [], shown = null, box = null, timer = 0, busy = false, stopped = false;
|
||||
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||
});
|
||||
}
|
||||
function when(iso) {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || "");
|
||||
return m ? m[2] + "/" + m[3] + " " + m[4] + ":" + m[5] : "";
|
||||
}
|
||||
function who(email) {
|
||||
const id = String(email || "").split("@")[0];
|
||||
return id ? id.charAt(0).toUpperCase() + id.slice(1) : "";
|
||||
}
|
||||
function schedule() { clearTimeout(timer); if (!stopped) timer = setTimeout(poll, POLL_MS); }
|
||||
|
||||
async function poll() {
|
||||
if (busy || stopped) return;
|
||||
if (document.hidden) { schedule(); return; }
|
||||
busy = true;
|
||||
try {
|
||||
const res = await fetch("/notice/api/pending", { headers: { Accept: "application/json" }, credentials: "same-origin" });
|
||||
if (res.status === 401 || res.status === 403 || res.status === 503 || res.status === 404) { stopped = true; return; }
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
queue = Array.isArray(data.notices) ? data.notices : [];
|
||||
// 다른 탭·다른 곳에서 확인했거나 취소된 공지는 닫는다
|
||||
if (shown && !queue.some(function (n) { return n.id === shown.id; })) close();
|
||||
if (!shown && queue.length) open(queue[0]);
|
||||
else if (shown) paintCount();
|
||||
} catch (_) {
|
||||
// 네트워크 오류는 다음 주기에 다시
|
||||
} finally {
|
||||
busy = false;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
|
||||
function paintCount() {
|
||||
if (!box || !shown) return;
|
||||
const i = queue.findIndex(function (n) { return n.id === shown.id; });
|
||||
const c = box.querySelector(".erp-notice-count");
|
||||
c.textContent = queue.length > 1 ? (i + 1) + " / " + queue.length : "";
|
||||
c.hidden = queue.length <= 1;
|
||||
}
|
||||
function open(n) {
|
||||
shown = n;
|
||||
if (!box) {
|
||||
box = document.createElement("div");
|
||||
box.className = "erp-notice-backdrop";
|
||||
box.innerHTML =
|
||||
'<div class="erp-notice-card" role="alertdialog" aria-modal="true" aria-labelledby="erp-notice-title">' +
|
||||
'<div class="erp-notice-head"><span class="erp-notice-badge">긴급 공지</span><span class="erp-notice-count" hidden></span></div>' +
|
||||
'<h2 class="erp-notice-title" id="erp-notice-title"></h2>' +
|
||||
'<div class="erp-notice-body"></div>' +
|
||||
'<p class="erp-notice-error" role="alert" hidden></p>' +
|
||||
'<div class="erp-notice-foot"><span class="erp-notice-meta"></span>' +
|
||||
'<button type="button" class="erp-notice-ok">확인</button></div></div>';
|
||||
document.body.appendChild(box); // 화면 배율(.erp-app zoom) 밖 — 늘 화면 정가운데
|
||||
box.querySelector(".erp-notice-ok").addEventListener("click", ack);
|
||||
// [확인] 전에는 닫지 않는다 — Esc 는 막고, 포커스는 창 안에
|
||||
box.addEventListener("keydown", function (e) {
|
||||
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); }
|
||||
if (e.key === "Tab") { e.preventDefault(); box.querySelector(".erp-notice-ok").focus(); }
|
||||
});
|
||||
}
|
||||
box.querySelector(".erp-notice-title").textContent = n.title || "";
|
||||
box.querySelector(".erp-notice-body").innerHTML = n.body_html || ""; // 서버가 정리한 HTML
|
||||
box.querySelector(".erp-notice-meta").textContent =
|
||||
[who(n.created_by), when(n.show_at)].filter(Boolean).join(" · ");
|
||||
box.querySelector(".erp-notice-error").hidden = true;
|
||||
box.querySelector(".erp-notice-body").scrollTop = 0;
|
||||
box.hidden = false;
|
||||
paintCount();
|
||||
const ok = box.querySelector(".erp-notice-ok");
|
||||
ok.disabled = false;
|
||||
ok.focus();
|
||||
}
|
||||
function close() {
|
||||
shown = null;
|
||||
if (box) box.hidden = true;
|
||||
}
|
||||
async function ack() {
|
||||
if (!shown) return;
|
||||
const n = shown, ok = box.querySelector(".erp-notice-ok"), err = box.querySelector(".erp-notice-error");
|
||||
ok.disabled = true;
|
||||
err.hidden = true;
|
||||
try {
|
||||
const res = await fetch("/notice/api/" + n.id + "/ack", { method: "POST", credentials: "same-origin" });
|
||||
if (!res.ok && res.status !== 404) throw new Error("HTTP " + res.status); // 404 = 취소·삭제됨 — 닫는다
|
||||
try { localStorage.setItem("erp_notice_ack", String(n.id) + ":" + Date.now()); } catch (_) {}
|
||||
queue = queue.filter(function (x) { return x.id !== n.id; });
|
||||
if (queue.length) open(queue[0]); else close();
|
||||
} catch (e) {
|
||||
err.textContent = "확인을 저장하지 못했습니다. 다시 눌러 주세요. (" + e.message + ")";
|
||||
err.hidden = false;
|
||||
ok.disabled = false;
|
||||
ok.focus();
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("storage", function (e) { if (e.key === "erp_notice_ack") poll(); });
|
||||
document.addEventListener("visibilitychange", function () { if (!document.hidden) poll(); });
|
||||
if (window.__ERP_NOTICE_TEST__) window.__erpNotice = { poll: poll, state: function () { return { queue: queue, shown: shown, stopped: stopped }; } };
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", poll);
|
||||
else poll();
|
||||
})();
|
||||
@@ -0,0 +1,33 @@
|
||||
/* 마감 지난 내 업무 알림 — ERP 모든 화면 위쪽 가운데(erp-overdue.js). body 에 붙어 화면 배율(.erp-app zoom) 밖. 긴급 공지(6000)보다 아래. */
|
||||
.erp-overdue {
|
||||
position: fixed; top: 12px; left: 50%; transform: translateX(-50%); z-index: 5500;
|
||||
width: min(560px, calc(100vw - 32px)); box-sizing: border-box;
|
||||
padding: 12px 14px 10px; border-radius: 12px; background: #fff; color: #1e1f21;
|
||||
border: 1px solid #f3c5c6; border-top: 4px solid #e5484d;
|
||||
box-shadow: 0 12px 36px rgba(16, 24, 40, .22);
|
||||
font-size: 13.5px; animation: erp-overdue-in .22s ease-out;
|
||||
}
|
||||
.erp-overdue[hidden] { display: none; }
|
||||
@keyframes erp-overdue-in { from { opacity: 0; transform: translate(-50%, -10px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
||||
.erp-overdue-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
|
||||
.erp-overdue-head b { flex: 1 1 auto; font-size: 14.5px; color: #c62a2f; }
|
||||
.erp-overdue-ic { font-size: 17px; }
|
||||
.erp-overdue-close {
|
||||
flex: none; border: 1px solid #d8dce2; background: #fff; color: #4b5059; border-radius: 8px;
|
||||
padding: 4px 10px; font: inherit; font-size: 12px; cursor: pointer;
|
||||
}
|
||||
.erp-overdue-close:hover { background: #f3f4f6; }
|
||||
.erp-overdue-list { display: flex; flex-direction: column; max-height: 50vh; overflow-y: auto; }
|
||||
.erp-overdue-item {
|
||||
display: flex; align-items: center; gap: 10px; padding: 7px 6px; border-radius: 8px;
|
||||
color: inherit; text-decoration: none;
|
||||
}
|
||||
.erp-overdue-item:hover { background: #fdf2f2; }
|
||||
.erp-overdue-dot { flex: none; width: 9px; height: 9px; border-radius: 3px; }
|
||||
.erp-overdue-text { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; }
|
||||
.erp-overdue-text b, .erp-overdue-text small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.erp-overdue-text b { font-weight: 600; }
|
||||
.erp-overdue-text small { color: #6b7079; font-size: 11.5px; }
|
||||
.erp-overdue-late { flex: none; color: #c62a2f; font-size: 12px; font-weight: 700; white-space: nowrap; }
|
||||
.erp-overdue-more { padding: 6px; font-size: 12px; color: #3b6fd8; text-decoration: none; }
|
||||
.erp-overdue-more:hover { text-decoration: underline; }
|
||||
@@ -0,0 +1,106 @@
|
||||
// 마감 지난 내 업무 알림 — ERP 모든 화면 위쪽 가운데(2026-10-13).
|
||||
// · GET /project/api/my-overdue — 내가 담당인 미완료 업무 중 마감일이 오늘(한국시간) 이전인 것(지금 볼 수 있는 것만).
|
||||
// · [닫기] 하면 1시간 동안 다시 띄우지 않는다(이 브라우저의 모든 탭 — localStorage). 1시간이 지나면 다시 나타난다.
|
||||
// 단, 닫을 때 없던 업무가 새로 마감을 넘기면 1시간을 기다리지 않고 바로 띄운다.
|
||||
// · 5분마다·창을 다시 볼 때 확인. 다 완료하면 알림은 사라진다.
|
||||
// · Project 권한이 없거나(403) 로그아웃(401)·모듈 미설정(503)이면 조용히 멈춘다. iframe(수신함 업무 창 등) 안에서는 돌지 않는다.
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.top !== window) return;
|
||||
const POLL_MS = 5 * 60 * 1000;
|
||||
const SNOOZE_MS = 60 * 60 * 1000;
|
||||
const KEY = "erp_overdue_snooze"; // {until: ms, ids: [업무 id]}
|
||||
const MAX_ROWS = 5;
|
||||
let box = null, timer = 0, busy = false, stopped = false, last = [], memSnooze = null;
|
||||
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||
});
|
||||
}
|
||||
function readSnooze() {
|
||||
try { return JSON.parse(localStorage.getItem(KEY) || "null") || memSnooze; } catch (_) { return memSnooze; }
|
||||
}
|
||||
function writeSnooze(v) {
|
||||
memSnooze = v;
|
||||
try { localStorage.setItem(KEY, JSON.stringify(v)); } catch (_) {}
|
||||
}
|
||||
// 닫은 지 1시간이 안 됐고, 지금 목록이 닫을 때 본 업무뿐이면 쉰다.
|
||||
function snoozed(tasks) {
|
||||
const s = readSnooze();
|
||||
if (!s || !(Date.now() < s.until)) return false;
|
||||
const seen = s.ids || [];
|
||||
return tasks.every(function (t) { return seen.indexOf(t.id) >= 0; });
|
||||
}
|
||||
function daysLate(due, today) {
|
||||
const a = Date.parse(String(due).slice(0, 10) + "T00:00:00Z"), b = Date.parse(String(today).slice(0, 10) + "T00:00:00Z");
|
||||
return isNaN(a) || isNaN(b) ? 0 : Math.round((b - a) / 86400000);
|
||||
}
|
||||
function md(due) {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(due || "");
|
||||
return m ? parseInt(m[2], 10) + "/" + parseInt(m[3], 10) : "";
|
||||
}
|
||||
function schedule() { clearTimeout(timer); if (!stopped) timer = setTimeout(poll, POLL_MS); }
|
||||
|
||||
async function poll() {
|
||||
if (busy || stopped) return;
|
||||
if (document.hidden) { schedule(); return; }
|
||||
busy = true;
|
||||
try {
|
||||
const res = await fetch("/project/api/my-overdue", { headers: { Accept: "application/json" }, credentials: "same-origin" });
|
||||
if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 503) { stopped = true; hide(); return; }
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
last = Array.isArray(data.tasks) ? data.tasks : [];
|
||||
if (!last.length || snoozed(last)) hide();
|
||||
else show(last, data.today || "");
|
||||
} catch (_) {
|
||||
// 네트워크 오류는 다음 주기에 다시
|
||||
} finally {
|
||||
busy = false;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
|
||||
function show(tasks, today) {
|
||||
if (!box) {
|
||||
box = document.createElement("div");
|
||||
box.className = "erp-overdue";
|
||||
box.setAttribute("role", "alert");
|
||||
document.body.appendChild(box); // 화면 배율(.erp-app zoom) 밖 — 늘 화면 위쪽 가운데
|
||||
box.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-overdue-close]")) dismiss();
|
||||
});
|
||||
}
|
||||
const rows = tasks.slice(0, MAX_ROWS).map(function (t) {
|
||||
const late = daysLate(t.due_date, today);
|
||||
const where = [t.project_name, t.parent_title ? "상위: " + t.parent_title : ""].filter(Boolean).join(" · ");
|
||||
return '<a class="erp-overdue-item" href="/project/t/' + encodeURIComponent(t.id) + '">' +
|
||||
'<span class="erp-overdue-dot" style="background:' + esc(t.project_color || "#e5484d") + '"></span>' +
|
||||
'<span class="erp-overdue-text"><b>' + esc(t.title || "(제목 없음)") + "</b><small>" + esc(where) + "</small></span>" +
|
||||
'<span class="erp-overdue-late">마감 ' + esc(md(t.due_date)) + (late > 0 ? " · " + late + "일 지남" : "") + "</span></a>";
|
||||
}).join("");
|
||||
const more = tasks.length > MAX_ROWS
|
||||
? '<a class="erp-overdue-more" href="/project/">그 밖에 ' + (tasks.length - MAX_ROWS) + "건 — 내 업무에서 보기</a>" : "";
|
||||
box.innerHTML =
|
||||
'<div class="erp-overdue-head"><span class="erp-overdue-ic" aria-hidden="true">⏰</span>' +
|
||||
'<b>마감이 지난 내 업무 ' + tasks.length + "건</b>" +
|
||||
'<button type="button" class="erp-overdue-close" data-overdue-close>닫기</button></div>' +
|
||||
'<div class="erp-overdue-list">' + rows + more + "</div>";
|
||||
box.hidden = false;
|
||||
}
|
||||
function hide() { if (box) box.hidden = true; }
|
||||
function dismiss() {
|
||||
writeSnooze({ until: Date.now() + SNOOZE_MS, ids: last.map(function (t) { return t.id; }) });
|
||||
hide();
|
||||
// 1시간 뒤 바로 다시 확인(5분 주기를 기다리지 않게)
|
||||
setTimeout(poll, SNOOZE_MS + 1000);
|
||||
}
|
||||
|
||||
// 다른 탭에서 닫으면 이 탭도 닫는다.
|
||||
window.addEventListener("storage", function (e) { if (e.key === KEY && last.length && snoozed(last)) hide(); });
|
||||
document.addEventListener("visibilitychange", function () { if (!document.hidden) poll(); });
|
||||
if (window.__ERP_OVERDUE_TEST__) window.__erpOverdue = { poll: poll, state: function () { return { last: last, stopped: stopped, box: box }; } };
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", poll);
|
||||
else poll();
|
||||
})();
|
||||
@@ -7,6 +7,7 @@
|
||||
--perf-line: var(--color-subtle-ash);
|
||||
--perf-soft: #fafafa;
|
||||
--perf-up: #0f8a3a;
|
||||
--perf-good: #1a56db; /* 증감 표시 좋음(파랑) — 나쁨은 --perf-down(빨강) */
|
||||
--perf-down: var(--color-callout-red);
|
||||
--perf-sat: #1d4ed8;
|
||||
--perf-sun: var(--color-callout-red);
|
||||
@@ -24,13 +25,51 @@
|
||||
.perf-center { text-align: center; }
|
||||
|
||||
/* 탭 */
|
||||
.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-tab {
|
||||
padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray);
|
||||
border-bottom: 2px solid transparent; margin-bottom: -1px;
|
||||
/* [매출 실적] [광고비] — 큰 알약 탭 둘, 고른 탭은 채운 색(매출 = 검정, 광고비 = 주황)으로 한눈에 구분.
|
||||
설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols "settings"). */
|
||||
.perf-tabs {
|
||||
display: flex; align-items: center; gap: 8px; padding-bottom: 10px; border-bottom: 1px solid var(--perf-line);
|
||||
}
|
||||
.perf-tab:hover { color: var(--color-rich-black); }
|
||||
.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); }
|
||||
.perf-tabs-main {
|
||||
display: inline-flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--color-ghost-gray, #f3f3f3);
|
||||
}
|
||||
.perf-tab {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 7px 16px; border-radius: 9px;
|
||||
font-size: 14px; font-weight: 600; color: var(--color-midtone-gray); text-decoration: none;
|
||||
transition: background .15s, color .15s, box-shadow .15s;
|
||||
}
|
||||
.perf-tab .material-symbols-outlined { font-size: 19px; }
|
||||
.perf-tab:hover { color: var(--color-rich-black); background: rgba(255, 255, 255, .7); }
|
||||
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
|
||||
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
|
||||
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
|
||||
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-tab-gear {
|
||||
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
|
||||
border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none;
|
||||
}
|
||||
.perf-tab-gear .material-symbols-outlined { font-size: 22px; }
|
||||
.perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); }
|
||||
.perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); }
|
||||
|
||||
/* 광고비 화면 — 주황 강조(매출 실적과 구분) */
|
||||
.perf, .perf-modal { --perf-ad: #d9480f; }
|
||||
.perf-ads .perf-kpi.is-primary { border-color: var(--perf-ad); box-shadow: inset 4px 0 0 var(--perf-ad); }
|
||||
.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ads .perf-chart .bar { fill: var(--perf-ad); }
|
||||
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
|
||||
/* "광고비(ROAS%)" — ROAS 는 작게 옅게 붙인다. 입력 중엔 숫자처럼 자리만 남기고 숨김 */
|
||||
.perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); }
|
||||
.perf-row-total .perf-roas { color: #bbb; }
|
||||
.perf .perf-main td.is-editing .perf-roas { visibility: hidden; }
|
||||
/* 네이버 머리글 = 일자별 보고서 항목 보기 버튼 */
|
||||
.perf-detail-btn { display: inline-flex; align-items: center; gap: 3px; border: 0; background: transparent; font: inherit;
|
||||
font-weight: 600; color: var(--perf-ad); cursor: pointer; padding: 2px 4px; border-radius: 6px; }
|
||||
.perf-detail-btn .material-symbols-outlined { font-size: 16px; }
|
||||
.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; }
|
||||
.perf-detail-table th, .perf-detail-table td { white-space: nowrap; }
|
||||
.perf-ad-upload-btn { margin-left: auto; }
|
||||
.perf-kpi-pct { font-size: 26px; font-weight: 700; }
|
||||
|
||||
/* 도구 막대 */
|
||||
.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
@@ -75,6 +114,15 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-notice[hidden] { display: none; }
|
||||
.perf-notice.is-warn { background: #fff7f5; border-color: #f3d2ca; }
|
||||
.perf-notice.is-ok { background: #f3fbf5; border-color: #cdeccf; }
|
||||
/* 수동 입력 엑셀 업로드 — 버튼은 표시 기준 버튼 바로 왼쪽, 창 안 파일 칸·오류 목록 */
|
||||
.perf-manual-upload-btn { margin-left: auto; }
|
||||
/* 엑셀 초록(쿠팡 [엑셀 다운로드] 와 같은 색) — .erp-btn-outline 을 이기도록 .erp-btn 과 함께 */
|
||||
.erp-btn.perf-manual-upload-btn { background: #217346; border-color: #217346; color: #fff; }
|
||||
.erp-btn.perf-manual-upload-btn:hover { background: #1a5c38; border-color: #1a5c38; color: #fff; }
|
||||
.perf-upload-file { width: 100%; box-sizing: border-box; }
|
||||
.perf-upload-result { margin-top: 10px; }
|
||||
.perf-upload-result .perf-notice { margin: 0; display: block; line-height: 1.6; }
|
||||
.perf-upload-errors { margin: 6px 0 0; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 12px; line-height: 1.6; color: #b42318; }
|
||||
.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
|
||||
|
||||
/* KPI */
|
||||
@@ -86,7 +134,7 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
|
||||
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
|
||||
.perf-delta { font-weight: 600; }
|
||||
.perf-delta.is-up { color: var(--perf-up); }
|
||||
.perf-delta.is-up { color: var(--perf-good); } /* is-up = 좋음(수수료는 줄어야 좋음, invert) */
|
||||
.perf-delta.is-down { color: var(--perf-down); }
|
||||
.perf-delta.is-flat { color: var(--color-midtone-gray); }
|
||||
|
||||
@@ -102,11 +150,12 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-table-wrap { overflow-x: auto; }
|
||||
.perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; }
|
||||
/* 열 제목 — 가운데·굵게·검정(2026-10-12) */
|
||||
.perf-table thead th {
|
||||
font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right;
|
||||
font-size: 12px; font-weight: 700; color: #000; text-align: center;
|
||||
background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0;
|
||||
}
|
||||
.perf-table thead th.perf-th-label { text-align: left; }
|
||||
.perf-table thead th.perf-th-label { text-align: center; }
|
||||
.perf-td-label { text-align: left; font-weight: 500; }
|
||||
.perf-num { text-align: right; }
|
||||
.perf-zero { color: #c9c9c9; }
|
||||
@@ -128,6 +177,19 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
|
||||
/* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */
|
||||
.perf .v { display: none; }
|
||||
/* 수동 입력 칸 — 설정에서 켠 쇼핑몰의 날짜 칸. 파란 숫자 = 수동 입력값, 입력 중엔 숫자 대신 입력칸 */
|
||||
.perf-manual-mark { font-size: 11px; color: #1a56db; font-weight: 400; }
|
||||
.perf-main td.is-manual-cell { cursor: text; position: relative; }
|
||||
.perf-main td.is-manual-cell:hover { background: #eef3ff; box-shadow: inset 0 0 0 1px #c7d6fb; }
|
||||
.perf-main td.is-manual-cell:focus { outline: 2px solid #1a56db; outline-offset: -2px; }
|
||||
.perf-main td.is-manual .v-gross { color: #1a56db; font-weight: 600; }
|
||||
.perf-main td.is-stale .v-commission, .perf-main td.is-stale .v-net { opacity: .4; }
|
||||
/* 입력칸은 칸 위에 겹쳐 띄운다(표 배치에서 빠짐) — 숫자는 자리만 남기고 숨겨 열 너비가 그대로 */
|
||||
.perf .perf-main td.is-editing .v { visibility: hidden; }
|
||||
.perf-manual-input { position: absolute; top: 2px; right: 2px; bottom: 2px; left: 2px; width: auto; min-width: 0; height: auto;
|
||||
box-sizing: border-box; margin: 0; padding: 0 6px; border: 1px solid #1a56db; border-radius: 4px;
|
||||
font: inherit; text-align: right; background: #fff; outline: none; }
|
||||
.perf-manual-help { margin: 8px 2px 0; font-size: 12px; }
|
||||
.perf[data-metric="gross"] .v-gross,
|
||||
.perf[data-metric="commission"] .v-commission,
|
||||
.perf[data-metric="net"] .v-net { display: inline; }
|
||||
@@ -205,6 +267,9 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-test-result.is-ok { color: #0f8a3a; }
|
||||
.perf-test-result.is-bad { color: var(--perf-down); }
|
||||
|
||||
@media (min-width: 1281px) {
|
||||
.perf-ads .perf-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* 광고비 KPI 4개 */
|
||||
}
|
||||
@media (max-width: 1280px) {
|
||||
.perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
+267
-7
@@ -236,15 +236,20 @@
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
const KEY = "perf_metric";
|
||||
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
|
||||
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
|
||||
const MANUAL_WORD = data.manual_word || "총매출";
|
||||
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
|
||||
|
||||
// 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다.
|
||||
function setMetric(m) {
|
||||
if (FIXED_METRIC) m = FIXED_METRIC;
|
||||
if (!METRIC_NAMES[m]) m = "gross";
|
||||
root.dataset.metric = m;
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b.dataset.metric === m);
|
||||
});
|
||||
try { localStorage.setItem(KEY, m); } catch (_) {}
|
||||
if (!FIXED_METRIC) { try { localStorage.setItem(KEY, m); } catch (_) {} }
|
||||
drawDaily(m);
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
@@ -253,6 +258,167 @@
|
||||
b.addEventListener("click", function () { setMetric(b.dataset.metric); });
|
||||
});
|
||||
|
||||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||||
const uploadBtn = document.getElementById("perf-manual-upload");
|
||||
if (uploadBtn) uploadBtn.addEventListener("click", function () {
|
||||
let saved = false;
|
||||
const m = openModal("수동 입력 엑셀 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||||
const shops = (data.manual_upload_names || []).map(esc).join(", ");
|
||||
m.body.innerHTML =
|
||||
'<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' +
|
||||
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" +
|
||||
'<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" +
|
||||
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="/performance/api/manual-sales/sample.xlsx" download>' +
|
||||
"샘플 파일 받기</a></p>" +
|
||||
'<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' +
|
||||
'<div class="perf-upload-result"></div>';
|
||||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||||
const out = m.body.querySelector(".perf-upload-result");
|
||||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||||
m.foot.appendChild(cancel);
|
||||
m.foot.appendChild(go);
|
||||
cancel.addEventListener("click", m.close);
|
||||
go.addEventListener("click", async function () {
|
||||
const f = fileInput.files && fileInput.files[0];
|
||||
if (!f) { out.innerHTML = '<p class="perf-notice is-warn">엑셀 파일을 고르세요.</p>'; return; }
|
||||
go.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">올리는 중…</p>';
|
||||
const fd = new FormData();
|
||||
fd.append("file", f);
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||||
go.disabled = false;
|
||||
return;
|
||||
}
|
||||
go.disabled = false;
|
||||
const ignored = body && body.ignored && body.ignored.length
|
||||
? '<p class="perf-muted" style="margin:6px 0 0">건너뛴 열: ' + esc(body.ignored.join(", ")) + "</p>" : "";
|
||||
if (!res.ok) {
|
||||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||||
const errs = body && body.errors && body.errors.length
|
||||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs + ignored;
|
||||
return;
|
||||
}
|
||||
saved = body.saved > 0;
|
||||
out.innerHTML = '<p class="perf-notice is-ok">' + (saved
|
||||
? fmt(body.saved) + "칸 반영 (" + esc(body.from === body.to ? body.from : body.from + " ~ " + body.to) + ")<br>" +
|
||||
esc(body.by_shop.map(function (s) { return s.name + " " + fmt(s.count) + "일"; }).join(" · "))
|
||||
: "반영할 값이 없습니다(값이 있는 칸이 없음).") + "</p>" + ignored +
|
||||
(saved ? '<p class="perf-muted" style="margin:6px 0 0">창을 닫으면 표·합계·그래프가 다시 계산됩니다.</p>' : "");
|
||||
fileInput.value = "";
|
||||
});
|
||||
});
|
||||
|
||||
// 광고비 파일 업로드 — 채널(양식이 정해진 채널만)을 고르고 파일을 올리면 파일에 있는 날만 덮어쓴다.
|
||||
// 잘못된 줄이 있으면 서버가 아무것도 저장하지 않고 줄 위치 목록을 돌려준다.
|
||||
const adUploadBtn = document.getElementById("perf-ad-upload");
|
||||
if (adUploadBtn) adUploadBtn.addEventListener("click", function () {
|
||||
let saved = false;
|
||||
const chans = data.upload_channels || [];
|
||||
const m = openModal("광고비 파일 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||||
m.body.innerHTML =
|
||||
'<label class="perf-muted" style="display:block;margin:0 0 4px">채널</label>' +
|
||||
'<select class="erp-input perf-ad-channel" style="width:100%;margin:0 0 6px">' + chans.map(function (c) {
|
||||
return '<option value="' + esc(c.code) + '">' + esc(c.name) + "</option>";
|
||||
}).join("") + "</select>" +
|
||||
'<p class="perf-muted perf-ad-help" style="margin:0 0 10px"></p>' +
|
||||
'<input type="file" multiple class="erp-input perf-upload-file" accept=".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="광고 보고서 파일(여러 개 가능)" />' +
|
||||
'<p class="perf-muted" style="margin:6px 0 0">파일을 여러 개 고를 수 있습니다. 같은 날짜가 여러 파일에 있으면 파일 날짜(수정 시각)가 최신인 파일 값을 씁니다.</p>' +
|
||||
'<div class="perf-upload-result"></div>';
|
||||
const sel = m.body.querySelector(".perf-ad-channel");
|
||||
const help = m.body.querySelector(".perf-ad-help");
|
||||
function showHelp() {
|
||||
const c = chans.filter(function (x) { return x.code === sel.value; })[0];
|
||||
help.textContent = c ? c.help : "";
|
||||
}
|
||||
sel.addEventListener("change", showHelp);
|
||||
showHelp();
|
||||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||||
const out = m.body.querySelector(".perf-upload-result");
|
||||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||||
m.foot.appendChild(cancel);
|
||||
m.foot.appendChild(go);
|
||||
cancel.addEventListener("click", m.close);
|
||||
go.addEventListener("click", async function () {
|
||||
const picked = Array.prototype.slice.call(fileInput.files || []);
|
||||
if (!picked.length) { out.innerHTML = '<p class="perf-notice is-warn">파일을 고르세요.</p>'; return; }
|
||||
go.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">올리는 중… (' + picked.length + "개 파일)</p>";
|
||||
const fd = new FormData();
|
||||
picked.forEach(function (f) {
|
||||
fd.append("files", f);
|
||||
fd.append("modified", String(f.lastModified || 0)); // 같은 날짜는 파일 날짜가 최신인 파일 값
|
||||
});
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
|
||||
{ method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||||
go.disabled = false;
|
||||
return;
|
||||
}
|
||||
go.disabled = false;
|
||||
if (!res.ok) {
|
||||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||||
const errs = body && body.errors && body.errors.length
|
||||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs;
|
||||
return;
|
||||
}
|
||||
saved = body.saved > 0;
|
||||
// 업로드가 끝나면 창을 닫고 표·합계·그래프를 다시 그린다(onClose 새로고침). 청구금액이 없는 날짜·파일은 그냥 넘어간다.
|
||||
if (saved) { m.close(); return; }
|
||||
out.innerHTML = '<p class="perf-notice is-ok">청구금액이 있는 날짜가 없어 반영한 날이 없습니다.</p>';
|
||||
fileInput.value = "";
|
||||
});
|
||||
});
|
||||
|
||||
// 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||||
root.addEventListener("click", async function (e) {
|
||||
const btn = e.target.closest("[data-detail-channel]");
|
||||
if (!btn) return;
|
||||
const code = btn.dataset.detailChannel;
|
||||
const name = (data.names || {})[code] || code;
|
||||
const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true });
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
|
||||
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
|
||||
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간에 올린 보고서 자료가 없습니다.</p>'; return; }
|
||||
const cols = res.columns || [];
|
||||
const cell = function (v) {
|
||||
if (v == null || v === "") return '<span class="perf-zero">–</span>';
|
||||
return typeof v === "number" ? (Number.isInteger(v) ? fmt(v) : v.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })) : esc(v);
|
||||
};
|
||||
const WD = ["일", "월", "화", "수", "목", "금", "토"];
|
||||
const day = function (iso) {
|
||||
const d = new Date(iso + "T00:00:00");
|
||||
return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")";
|
||||
};
|
||||
m.body.innerHTML = '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||
res.rows.map(function (r) {
|
||||
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
|
||||
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
|
||||
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
|
||||
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") +
|
||||
"</tr></tfoot></table></div>" +
|
||||
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.</p>';
|
||||
} catch (err) {
|
||||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
}
|
||||
});
|
||||
|
||||
// 직접선택 / 쇼핑몰 필터
|
||||
const customBtn = document.getElementById("perf-custom-btn");
|
||||
const customForm = document.getElementById("perf-custom");
|
||||
@@ -333,6 +499,93 @@
|
||||
if (!td) return;
|
||||
openEvents(td.dataset.code, td.dataset.from, td.dataset.to);
|
||||
});
|
||||
|
||||
// ── 수동 입력(설정에서 켠 쇼핑몰) — 날짜 칸을 눌러 총매출 입력. Enter 저장 후 아래 칸 · Shift+Enter 위 칸 · Esc 취소.
|
||||
// 비우고 저장하면 그날은 다시 API 값. 저장은 칸마다 차례로, 입력을 마치면(다른 칸으로 안 넘어가면) 새로고침해
|
||||
// 합계·수수료·그래프를 서버 계산으로 다시 그린다.
|
||||
let manualDirty = false;
|
||||
let manualChain = Promise.resolve();
|
||||
function manualCells(code) {
|
||||
return Array.prototype.slice.call(root.querySelectorAll('td.is-manual-cell[data-manual-code="' + code + '"]'));
|
||||
}
|
||||
function digitsOf(td) { return td.dataset.manualValue || ""; }
|
||||
function finishManual() {
|
||||
setTimeout(function () {
|
||||
if (root.querySelector(".perf-manual-input")) return; // 다른 칸으로 넘어감
|
||||
manualChain.then(function () { if (manualDirty) location.reload(); });
|
||||
}, 120);
|
||||
}
|
||||
function saveManual(td, text) {
|
||||
const raw = String(text || "").replace(/[,\s원]/g, "");
|
||||
const was = digitsOf(td);
|
||||
if (raw !== "" && !/^-?\d+$/.test(raw)) return Promise.reject(new Error("숫자(원)만 입력하세요."));
|
||||
if (raw === was) return Promise.resolve(false); // 바뀐 것 없음(빈 칸 그대로 포함)
|
||||
const job = manualChain.then(function () {
|
||||
return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" +
|
||||
encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : Number(raw) });
|
||||
}).then(function (res) {
|
||||
const manual = res.manual == null ? "" : String(res.manual);
|
||||
td.dataset.manualValue = manual;
|
||||
td.classList.toggle("is-manual", manual !== "");
|
||||
td.classList.remove("is-upload");
|
||||
const ro = td.querySelector(".perf-roas"); // 광고비가 바뀌면 ROAS 는 새로고침 때 다시 계산
|
||||
if (ro) ro.remove();
|
||||
td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")"
|
||||
: "눌러 " + MANUAL_WORD + " 직접 입력";
|
||||
const g = td.querySelector(".v-gross");
|
||||
if (g) g.innerHTML = won(res.amount);
|
||||
td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산
|
||||
manualDirty = true;
|
||||
return true;
|
||||
});
|
||||
manualChain = job.catch(function () {});
|
||||
return job;
|
||||
}
|
||||
function editManual(td) {
|
||||
if (td.querySelector(".perf-manual-input")) return;
|
||||
const input = el("input", { type: "text", inputmode: "numeric", class: "perf-manual-input",
|
||||
"aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " " + MANUAL_WORD });
|
||||
input.value = digitsOf(td);
|
||||
const g = td.querySelector(".v-gross");
|
||||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || MANUAL_WORD;
|
||||
td.classList.add("is-editing");
|
||||
td.appendChild(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
let done = false;
|
||||
function close() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
input.remove();
|
||||
td.classList.remove("is-editing");
|
||||
}
|
||||
function commit(step) {
|
||||
if (done) return;
|
||||
const val = input.value;
|
||||
close();
|
||||
const cells = manualCells(td.dataset.manualCode);
|
||||
const next = step ? cells[cells.indexOf(td) + step] : null;
|
||||
if (next) editManual(next);
|
||||
saveManual(td, val).catch(function (err) {
|
||||
alertMsg("저장 실패(" + td.dataset.date + "): " + err.message);
|
||||
}).then(finishManual);
|
||||
}
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (e.isComposing) return;
|
||||
if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); commit(e.shiftKey ? -1 : 1); }
|
||||
else if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); commit(e.key === "ArrowUp" ? -1 : 1); }
|
||||
else if (e.key === "Escape") { e.preventDefault(); close(); td.focus(); finishManual(); }
|
||||
});
|
||||
input.addEventListener("blur", function () { commit(0); });
|
||||
}
|
||||
root.addEventListener("click", function (e) {
|
||||
const td = e.target.closest("td.is-manual-cell");
|
||||
if (td && !e.target.closest(".perf-manual-input")) editManual(td);
|
||||
});
|
||||
root.addEventListener("keydown", function (e) {
|
||||
const td = e.target.closest && e.target.closest("td.is-manual-cell");
|
||||
if (td && e.target === td && (e.key === "Enter" || e.key === "F2")) { e.preventDefault(); editManual(td); }
|
||||
});
|
||||
async function openEvents(code, from, to) {
|
||||
const name = (data.names || {})[code] || code;
|
||||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||||
@@ -388,7 +641,7 @@
|
||||
const pts = data.daily || [];
|
||||
const vals = pts.map(function (p) { return p[metric] || 0; });
|
||||
if (!pts.length || vals.every(function (v) { return !v; })) {
|
||||
box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>';
|
||||
box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
|
||||
return;
|
||||
}
|
||||
const W = 640, H = 230, L = 48, R = 8, T = 10, B = 26;
|
||||
@@ -419,7 +672,7 @@
|
||||
if (!box) return;
|
||||
const rows = (data.share || []).slice().sort(function (a, b) { return (b[metric] || 0) - (a[metric] || 0); });
|
||||
const total = rows.reduce(function (s, r) { return s + Math.max(0, r[metric] || 0); }, 0);
|
||||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>'; return; }
|
||||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>"; return; }
|
||||
const W = 640, rowH = 22, L = 120, R = 150, H = rows.length * rowH + 6;
|
||||
const maxV = Math.max.apply(null, rows.map(function (r) { return Math.max(0, r[metric] || 0); })) || 1;
|
||||
let g = "";
|
||||
@@ -987,7 +1240,7 @@
|
||||
}
|
||||
});
|
||||
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑·쿠팡) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
const probe = document.getElementById("perf-probe");
|
||||
if (probe) probe.addEventListener("click", async function () {
|
||||
const day = document.getElementById("perf-probe-date").value;
|
||||
@@ -997,14 +1250,21 @@
|
||||
const codeSel = document.getElementById("perf-probe-code");
|
||||
const code = codeSel ? codeSel.value : "elevenst";
|
||||
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||
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; }
|
||||
const summary = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
|
||||
// 원본 확인은 최대 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>" +
|
||||
@@ -1038,7 +1298,7 @@
|
||||
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
|
||||
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">환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불</h4>' +
|
||||
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) {
|
||||
|
||||
@@ -287,19 +287,25 @@
|
||||
if (merged.length) items.push({ label: "병합 해제", icon: opts.icon("call_split"), onClick: () => unmergeCells(merged) });
|
||||
if (cells.some(c => editorOf(c).value)) items.push({ label: "내용 지우기 (Del)", icon: opts.icon("ink_eraser"), onClick: () => clearCells(cells) });
|
||||
if (saver) {
|
||||
// 주요 업무 칸에서 추가한 줄은 같은 항목 칸 안에 들어간다(항목 칸은 그대로 — 027 sameLabel)
|
||||
items.push(null,
|
||||
{ label: "위에 줄 추가", icon: opts.icon("add_row_above"), onClick: () => saver.addRow(cell.closest("tbody").dataset.section, cell.dataset.meetItem, "above") },
|
||||
{ label: "위에 줄 추가", icon: opts.icon("add_row_above"), onClick: () => saver.addRow(cell.closest("tbody").dataset.section, cell.dataset.meetItem, "above", { sameLabel: true }) },
|
||||
{ label: "아래에 줄 추가", icon: opts.icon("add_row_below"), onClick: () => {
|
||||
const rows = Array.from(cell.closest("tbody").rows), bottom = rows[rows.indexOf(cell.parentElement) + cell.rowSpan - 1];
|
||||
saver.addRow(cell.closest("tbody").dataset.section, bottom.dataset.item, "below");
|
||||
saver.addRow(cell.closest("tbody").dataset.section, bottom.dataset.item, "below", { sameLabel: true });
|
||||
} });
|
||||
if (cell.rowSpan === 1 && cells.length === 1 && saver.deleteRow) {
|
||||
items.push({ label: "줄 삭제", danger: true, icon: opts.icon("delete"), onClick: () => saver.deleteRow(cell.parentElement) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (items.length) items.push(null);
|
||||
items.push(...widthItems(td));
|
||||
if (items.length) { e.preventDefault(); opts.menu(e.clientX, e.clientY, items); }
|
||||
});
|
||||
return { bindSaver: s => { saver = s; }, widthItems: widthItems };
|
||||
// 줄 구조를 다시 끼운 뒤(refreshMeeting) — 새 칸에 열 너비 손잡이·이동 테두리, 너비 다시 적용, 선택 풀기
|
||||
function refresh() { anchor = null; clearSelection(); handles(); applyWidths(); }
|
||||
return { bindSaver: s => { saver = s; }, widthItems: widthItems, refresh: refresh };
|
||||
}
|
||||
window.PJMeetingCells = { init: init };
|
||||
})();
|
||||
|
||||
+171
-15
@@ -322,6 +322,15 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
.pj-col-assignee .pj-avatar { width: 20px; height: 20px; box-shadow: 0 0 0 1.5px #fff; }
|
||||
.pj-col-assignee .pj-gicon { font-size: 20px; color: var(--pj-ink-soft); }
|
||||
.pj-col-head-colored .pj-col-assignee .pj-gicon { color: #fff; }
|
||||
/* 관리 권한이면 눌러서 바로 기본 담당자 지정 — 없으면 점선 원 사람 아이콘 */
|
||||
.pj-col-assignee.is-editable { width: 24px; height: 24px; justify-content: center; border-radius: 50%; cursor: pointer; color: #6d6e6f; }
|
||||
.pj-col-assignee.is-editable:hover, .pj-col-assignee.is-editable:focus-visible { background: rgba(0,0,0,.08); outline: none; }
|
||||
.pj-col-assignee .pj-person-ic.is-empty { display: inline-flex; }
|
||||
.pj-col-assignee .pj-gicon.pj-person-ic { font-size: 20px; }
|
||||
.pj-col-assignee .pj-person-ic.is-empty svg { width: 20px; height: 20px; }
|
||||
.pj-col-assignee.is-empty { opacity: .55; }
|
||||
.pj-col-assignee.is-empty:hover { opacity: 1; color: #1e1f21; }
|
||||
.pj-list-group-head .pj-col-assignee { vertical-align: middle; margin-left: 8px; }
|
||||
.pj-stg-assignee-hint { display: block; margin: 4px 0 0; font-weight: 400; }
|
||||
/* 세션 기본 담당자 카드 — 고른 사람은 배경 강조 */
|
||||
.pj-stg-pick { cursor: pointer; }
|
||||
@@ -370,7 +379,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
.pj-col-collapse svg { width: 18px; height: 18px; }
|
||||
.pj-col.is-collapsed { flex-basis: 48px; width: 48px; padding: 0; }
|
||||
.pj-col.is-collapsed .pj-col-head { flex-direction: column; gap: 10px; padding: 10px 8px; margin: 0; border: 0; border-radius: 5px; }
|
||||
.pj-col.is-collapsed .pj-col-name { writing-mode: vertical-rl; text-orientation: mixed; overflow-wrap: anywhere; max-height: 240px; }
|
||||
.pj-col.is-collapsed .pj-col-name { writing-mode: vertical-rl; text-orientation: mixed; overflow-wrap: anywhere; max-height: 240px; font-weight: 400; }
|
||||
.pj-col.is-collapsed .pj-col-count { writing-mode: vertical-rl; }
|
||||
.pj-col.is-collapsed .pj-col-body,
|
||||
.pj-col.is-collapsed .pj-col-addtask,
|
||||
@@ -435,6 +444,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
}
|
||||
.pj-tasknew-meta button:hover { background: #f1f2f4; }
|
||||
.pj-tasknew-meta .pj-avatar { width: 20px; height: 20px; }
|
||||
.pj-tasknew-meta .pj-tasknew-fol { gap: 1px; padding: 0 2px; border-radius: 12px; }
|
||||
.pj-tasknew-meta .pj-tasknew-fol .pj-gicon { font-size: 20px; }
|
||||
.pj-tasknew[aria-busy="true"] { opacity: .65; }
|
||||
/* 하위 업무 한 줄 드래그 — 끄는 줄은 흐리게, 놓을 수 있는 카드는 보라 테두리 */
|
||||
.pj-card-sub[draggable="true"] .pj-card-sub-title { cursor: grab; }
|
||||
@@ -480,6 +491,14 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
.pj-card-cover img { display: block; width: 100%; height: 100%; object-fit: cover; pointer-events: none; }
|
||||
.pj-card.has-cover .pj-card-head { border-radius: 0; }
|
||||
.pj-card-meta .pj-card-assignee.is-empty svg, .pj-card-meta .pj-card-due.is-empty svg { width: 24px; height: 24px; }
|
||||
/* 카드 협업자(담당자 오른쪽) — 비어 있으면 카드에 마우스를 올릴 때만 점선 원 두 사람 아이콘 */
|
||||
.pj-card-meta .pj-card-fol { display: inline-flex; align-items: center; gap: 1px; min-height: 24px; color: #6d6e6f; }
|
||||
.pj-card-meta .pj-card-fol.is-empty { justify-content: center; width: 26px; height: 26px; padding: 0; margin: -2px 0; border-radius: 50%; }
|
||||
.pj-card-meta .pj-card-fol > svg { width: 24px; height: 24px; }
|
||||
.pj-card-meta .pj-card-fol img.pj-person-ic { width: 20px; height: 20px; border-radius: 50%; }
|
||||
.pj-card-meta .pj-card-fol .pj-gicon { font-size: 22px; }
|
||||
.pj-card:hover .pj-card-meta .pj-card-fol.is-empty { opacity: 1; }
|
||||
.pj-card-meta .pj-card-fol.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
.pj-pri { padding: 1px 7px; border-radius: 999px; font-size: 10px; font-weight: 700; }
|
||||
.pj-pri-high { background: #fbe3df; color: #c22b10; }
|
||||
.pj-pri-low { background: #e6eef0; color: #4a6066; }
|
||||
@@ -501,6 +520,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
}
|
||||
.pj-list-group-caret { font-size: 18px; color: var(--pj-ink-soft); }
|
||||
.pj-list-group-name { font-weight: 700; }
|
||||
.pj-list-group-head.is-collapsed .pj-list-group-name { font-weight: 400; } /* 접힌 섹션은 보통 굵기 */
|
||||
.pj-list-group-count {
|
||||
color: var(--pj-ink-soft); font-weight: 700; font-size: 11px; background: #eef0f2;
|
||||
border-radius: 999px; min-width: 20px; height: 20px; padding: 0 6px;
|
||||
@@ -1265,6 +1285,18 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-card-sub:hover .pj-card-sub-av.is-empty { opacity: 1; }
|
||||
.pj-card-sub-av.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
.pj-card-sub-empty { padding: 8px 4px; font-size: 12px; color: #9aa1a9; }
|
||||
/* 카드 세부 업무 줄 협업자(담당자 오른쪽) — 없으면 줄에 마우스를 올릴 때만 점선 원 두 사람 */
|
||||
.pj-card-sub-fol {
|
||||
flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; gap: 1px;
|
||||
min-width: 24px; height: 24px; padding: 0 2px; border-radius: 12px; cursor: pointer; color: #6d6e6f;
|
||||
}
|
||||
.pj-card-sub-fol img.pj-person-ic { width: 20px; height: 20px; border-radius: 50%; }
|
||||
.pj-card-sub-fol .pj-gicon { font-size: 20px; }
|
||||
.pj-card-sub-fol > svg { width: 20px; height: 20px; }
|
||||
.pj-card-sub-fol:not(.is-empty):hover { background: #eceef0; }
|
||||
.pj-card-sub-fol.is-empty { opacity: 0; transition: opacity .12s; }
|
||||
.pj-card-sub:hover .pj-card-sub-fol.is-empty { opacity: 1; }
|
||||
.pj-card-sub-fol.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
/* 카드 하위 작업 맨 아래 "+ 하위 작업 추가"와 새 줄 입력(아사나) */
|
||||
.pj-card-subnew {
|
||||
display: flex; align-items: center; gap: 6px; min-height: 36px; padding: 2px 4px;
|
||||
@@ -1277,9 +1309,10 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
padding: 4px 0; font-size: 13px; font-family: inherit; color: var(--pj-ink);
|
||||
}
|
||||
.pj-card-subnew-title::placeholder { color: #9aa1a9; }
|
||||
/* 새 줄의 마감일·담당자 아이콘은 늘 보인다(기존 줄은 마우스를 올릴 때만) */
|
||||
/* 새 줄의 마감일·담당자·협업자 아이콘은 늘 보인다(기존 줄은 마우스를 올릴 때만) */
|
||||
.pj-card-subnew .pj-card-sub-due.is-empty,
|
||||
.pj-card-subnew .pj-card-sub-av.is-empty { opacity: 1; }
|
||||
.pj-card-subnew .pj-card-sub-av.is-empty,
|
||||
.pj-card-subnew .pj-card-sub-fol.is-empty { opacity: 1; }
|
||||
.pj-card-subadd {
|
||||
display: inline-flex; align-items: center; gap: 4px; margin: 6px 0 2px; padding: 4px 6px;
|
||||
border: none; background: transparent; border-radius: 6px; cursor: pointer;
|
||||
@@ -1413,7 +1446,7 @@ label.pj-desc-fmtbtn {
|
||||
}
|
||||
.pj-subtask-title:hover, .pj-subtask-title:focus { border-color: #d8dce2 !important; background: #fff; }
|
||||
.pj-subtask-fill { flex: 1 1 0; align-self: stretch; min-width: 8px; }
|
||||
/* 마감일 — 날짜 글자만(아사나). 없으면 줄에 마우스를 올릴 때만 점선 원 달력 아이콘 */
|
||||
/* 마감일 — 날짜 글자만(아사나). 없으면 점선 원 달력 아이콘을 협업자 아이콘처럼 늘 옅게(줄 hover 때 진하게, 2026-10-14) */
|
||||
.pj-subtask-due {
|
||||
flex: 0 0 auto; white-space: nowrap; font-size: 12px; color: var(--pj-ink-soft);
|
||||
padding: 2px 4px; border-radius: 4px; cursor: pointer;
|
||||
@@ -1423,7 +1456,7 @@ label.pj-desc-fmtbtn {
|
||||
.pj-subtask-due.is-soon { color: #3f8f6b; }
|
||||
.pj-subtask-due.is-empty {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; padding: 0;
|
||||
border-radius: 50%; color: #6d6e6f; opacity: 0; transition: opacity .12s;
|
||||
border-radius: 50%; color: #6d6e6f; opacity: .5; transition: opacity .12s;
|
||||
}
|
||||
.pj-subtask-row:hover .pj-subtask-due.is-empty { opacity: 1; }
|
||||
.pj-subtask-due.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
@@ -1437,6 +1470,20 @@ label.pj-desc-fmtbtn {
|
||||
.pj-subtask-av.is-empty { opacity: 0; transition: opacity .12s; }
|
||||
.pj-subtask-row:hover .pj-subtask-av.is-empty { opacity: 1; }
|
||||
.pj-subtask-av.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
/* 협업자 — 담당자 오른쪽. 없으면 점선 원 아이콘(줄 hover 때만), 있으면 첫 사람 + "+N" */
|
||||
.pj-subtask-fol {
|
||||
flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; gap: 1px;
|
||||
min-width: 26px; height: 26px; padding: 0 2px; border-radius: 13px; cursor: pointer; color: #6d6e6f;
|
||||
}
|
||||
.pj-subtask-fol[hidden] { display: none; }
|
||||
.pj-subtask-fol img.pj-person-ic { width: 22px; height: 22px; border-radius: 50%; }
|
||||
.pj-subtask-fol .pj-gicon { font-size: 22px; }
|
||||
.pj-subtask-fol-n { font-size: 11px; font-weight: 600; color: var(--pj-ink-soft); }
|
||||
.pj-subtask-fol:not(.is-empty):hover { background: #eceef0; }
|
||||
.pj-subtask-fol > svg { width: 22px; height: 22px; }
|
||||
.pj-subtask-fol.is-empty { opacity: .5; transition: opacity .12s; } /* 비어 있어도 늘 보인다(옅게) */
|
||||
.pj-subtask-row:hover .pj-subtask-fol.is-empty { opacity: 1; }
|
||||
.pj-subtask-fol.is-empty:hover { color: #1e1f21; background: #eceef0; }
|
||||
/* 하위 작업 열기(›) — 줄에 마우스를 올리면 진해진다 */
|
||||
.pj-subtask-open { flex: 0 0 auto; width: 26px; height: 26px; color: #9aa1a9; }
|
||||
.pj-subtask-row:hover .pj-subtask-open { color: var(--pj-ink); }
|
||||
@@ -1549,6 +1596,40 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
flex: 0 0 auto; width: 110px; font-size: 12px; font-weight: 500; padding: 3px 6px;
|
||||
border-color: #d8dce2; border-radius: 8px; background: #fff;
|
||||
}
|
||||
.pj-assignee-btn.pj-subtask-add-fol {
|
||||
flex: 0 0 auto; width: 110px; font-size: 12px; font-weight: 500; padding: 3px 6px;
|
||||
border-color: #d8dce2; border-radius: 8px; background: #fff;
|
||||
}
|
||||
.pj-assignee-btn.pj-subtask-add-fol img.pj-person-ic { width: 18px; height: 18px; }
|
||||
.pj-assignee-btn.pj-subtask-add-fol .pj-person-ic svg,
|
||||
.pj-assignee-btn.pj-subtask-add-fol > svg { width: 18px; height: 18px; flex: 0 0 auto; }
|
||||
.pj-assignee-btn.pj-subtask-add-fol .pj-subtask-fol-n { margin-left: -2px; }
|
||||
/* 세부 업무 추가 칸(2026-10-13) — 담당자·협업자·마감일은 글자 없는 동그라미 아이콘 버튼, 남는 폭은 제목 칸이 다 쓴다.
|
||||
(말풍선 = 담당자 이름·협업자 목록·날짜, 날짜를 고르면 아이콘 + 날짜) */
|
||||
.pj-subtask-form { flex-wrap: nowrap; align-items: center; gap: 4px; }
|
||||
.pj-subtask-form input[type="text"] { flex: 1 1 auto; min-width: 0; }
|
||||
.pj-subtask-form .pj-assignee-btn[data-for="pj-subtask-add-assignee"],
|
||||
.pj-subtask-form .pj-assignee-btn.pj-subtask-add-fol {
|
||||
width: auto; min-width: 32px; height: 32px; padding: 0 3px; gap: 1px; justify-content: center;
|
||||
border: none; border-radius: 16px; background: transparent; color: #6d6e6f;
|
||||
}
|
||||
.pj-subtask-form .pj-assignee-btn[data-for="pj-subtask-add-assignee"]:hover,
|
||||
.pj-subtask-form .pj-assignee-btn.pj-subtask-add-fol:hover { background: #eceef0; color: #1e1f21; }
|
||||
.pj-subtask-form .pj-assignee-btn .pj-assignee-btn-name { display: none; }
|
||||
.pj-subtask-form .pj-assignee-btn img.pj-person-ic { width: 24px; height: 24px; border-radius: 50%; }
|
||||
.pj-subtask-form .pj-assignee-btn .pj-person-ic svg,
|
||||
.pj-subtask-form .pj-assignee-btn.pj-subtask-add-fol > svg { width: 24px; height: 24px; }
|
||||
.pj-subtask-form .pj-date-btn:not(.is-icon-only) { height: 32px; padding: 0 8px; border: none; border-radius: 16px; background: #f3f4f6; }
|
||||
.pj-subtask-form .pj-date-btn:not(.is-icon-only) .material-symbols-outlined { font-size: 17px; }
|
||||
.pj-subtask-form #pj-subtask-add { flex: 0 0 auto; }
|
||||
.pj-subtask-form .pj-date-btn.is-icon-only { flex: 0 0 auto; width: 32px; padding: 0; }
|
||||
/* 추가 칸 아이콘 크기 통일 — 마감일·담당자·협업자 모두 24px(앞 규칙의 18px 보다 우선) */
|
||||
.pj-subtask-form .pj-assignee-btn[data-for] .pj-person-ic svg,
|
||||
.pj-subtask-form .pj-assignee-btn[data-for] img.pj-person-ic,
|
||||
.pj-subtask-form .pj-assignee-btn.pj-subtask-add-fol > svg,
|
||||
.pj-subtask-form .pj-assignee-btn.pj-subtask-add-fol img.pj-person-ic,
|
||||
.pj-subtask-form .pj-date-btn.is-icon-only > svg { width: 24px; height: 24px; }
|
||||
.pj-subtask-form .pj-assignee-btn .pj-gicon.pj-person-ic { font-size: 24px; }
|
||||
.pj-assignee-btn.pj-subtask-assignee img.pj-person-ic,
|
||||
.pj-assignee-btn[data-for="pj-subtask-add-assignee"] img.pj-person-ic { width: 18px; height: 18px; }
|
||||
.pj-assignee-btn.pj-subtask-assignee .pj-person-ic svg,
|
||||
@@ -1571,6 +1652,39 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
box-shadow: var(--pj-card-shadow); padding: 18px 20px 20px; min-width: 0;
|
||||
}
|
||||
.pj-dash-card-wide { grid-column: 1 / -1; }
|
||||
/* 업무 카드를 왼쪽 프로젝트에 끌어 놓을 때 — 놓일 프로젝트 줄 강조 */
|
||||
.pj-tree-row.is-task-drop { background: var(--pj-accent-tint); box-shadow: inset 0 0 0 2px var(--pj-accent); border-radius: 8px; }
|
||||
/* 다른 프로젝트로 이동 — 섹션 선택 창(body 에 붙음) */
|
||||
.pj-move-card { width: min(420px, 92vw); box-sizing: border-box; }
|
||||
.pj-move-card h3 { margin: 0 0 6px; }
|
||||
.pj-move-what { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
|
||||
.pj-move-dot { display: inline-block; width: 10px; height: 10px; border-radius: 3px; }
|
||||
.pj-move-label { margin: 12px 0 6px; font-size: 12.5px; font-weight: 700; color: var(--pj-ink-soft); }
|
||||
.pj-move-stages { display: flex; flex-direction: column; gap: 4px; max-height: 46vh; overflow-y: auto; }
|
||||
.pj-move-stage {
|
||||
display: flex; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--pj-border); border-radius: 8px;
|
||||
cursor: pointer; font-size: 13.5px;
|
||||
}
|
||||
.pj-move-stage:hover { background: #f5f6f8; }
|
||||
.pj-move-stage:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); }
|
||||
.pj-move-stage-name { flex: 1 1 auto; font-weight: 600; }
|
||||
.pj-move-stage small { flex-basis: 100%; color: var(--pj-ink-soft); font-size: 11.5px; }
|
||||
.pj-move-err { color: #c22b10; font-size: 12.5px; margin: 8px 0 0; }
|
||||
/* 업무 합계(프로젝트별) — 가로 막대 줄(채움 = 완료율) */
|
||||
.pj-dash-projbars { display: flex; flex-direction: column; gap: 4px; max-height: 210px; overflow-y: auto; margin: 0 -6px; }
|
||||
.pj-dash-projrow {
|
||||
display: grid; grid-template-columns: 10px minmax(0, 1fr) minmax(70px, 1.2fr) auto; align-items: center; gap: 8px;
|
||||
padding: 6px; border-radius: 8px; color: var(--pj-ink); text-decoration: none; font-size: 12.5px;
|
||||
}
|
||||
.pj-dash-projrow:hover { background: #f5f6f8; }
|
||||
.pj-dash-projdot { width: 10px; height: 10px; border-radius: 3px; }
|
||||
.pj-dash-projname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
|
||||
.pj-dash-projtrack { position: relative; height: 10px; border-radius: 5px; background: #e6e3f7; overflow: hidden; }
|
||||
.pj-dash-projtrack i {
|
||||
position: absolute; left: 0; top: 0; bottom: 0; width: 0; border-radius: 5px;
|
||||
background: var(--color-success-green, #2e9e5b); transition: width .6s cubic-bezier(.22,.9,.3,1);
|
||||
}
|
||||
.pj-dash-projval { color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; white-space: nowrap; font-size: 12px; }
|
||||
/* 담당자별 작업 합계 — 사람마다 메인·하위 세로 막대. 막대 = 그 작업 전체(100%), 초록 채움 = 완료율. 누르면 오른쪽 업무 목록 패널 */
|
||||
.pj-wl-legend { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin: -6px 0 14px; font-size: 12px; color: var(--pj-ink-soft); }
|
||||
.pj-wl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }
|
||||
@@ -1598,7 +1712,10 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
.pj-wl-col.is-sub .pj-wl-done { background: #5fbf86; }
|
||||
.pj-wl-kind { margin-top: 6px; font-size: 11px; color: var(--pj-ink-soft); white-space: nowrap; } /* "메인 작업"·"세부 작업" 한 줄 */
|
||||
.pj-wl-name { display: flex; flex-direction: column; align-items: center; margin-top: 4px; max-width: 110px; text-align: center; }
|
||||
.pj-wl-name b { font-size: 12.5px; font-weight: 600; color: var(--pj-ink); max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-wl-name-row { display: flex; align-items: center; justify-content: center; gap: 5px; max-width: 110px; }
|
||||
.pj-wl-name b { font-size: 12.5px; font-weight: 600; color: var(--pj-ink); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-wl-avatar.pj-avatar { width: 18px; height: 18px; }
|
||||
.pj-wl-avatar.pj-gicon { font-size: 18px; color: #9aa1a9; }
|
||||
.pj-wl-name small { font-size: 11px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
|
||||
/* 오른쪽 업무 목록 패널(body 에 붙음, 작업 편집 창(z 1000) 아래) */
|
||||
.pj-wl-drawer { position: fixed; inset: 0; z-index: 950; }
|
||||
@@ -1620,6 +1737,9 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
background: none; font: inherit; text-align: left; cursor: pointer; color: var(--pj-ink);
|
||||
}
|
||||
.pj-wl-item:hover { background: #f5f6f8; }
|
||||
.pj-wl-item.is-current { background: var(--pj-accent-tint); }
|
||||
/* 목록 패널에서 연 작업 창 — 패널 왼쪽에 붙어 열린다(right 는 JS 가 패널 폭으로). 슬라이드 중 패널 위로 넘치지 않게 자른다. */
|
||||
#pj-modal-task.pj-beside-drawer { overflow: hidden; background: rgba(20, 22, 26, .12); }
|
||||
.pj-wl-item .material-symbols-outlined { font-size: 19px; color: #9aa1ab; flex: none; }
|
||||
.pj-wl-item.is-done .material-symbols-outlined { color: var(--color-success-green, #2e9e5b); }
|
||||
.pj-wl-item.is-done .pj-wl-item-title { color: var(--pj-ink-soft); text-decoration: line-through; }
|
||||
@@ -1627,6 +1747,7 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
.pj-wl-item-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; }
|
||||
.pj-wl-item-main small { color: var(--pj-ink-soft); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-wl-item em { flex: none; font-style: normal; font-size: 12px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
|
||||
.pj-wl-item em.is-overdue { color: #d1242f; font-weight: 700; } /* 마감 지난 미완료 */
|
||||
.pj-dash-card-title { font-size: 13.5px; font-weight: 700; color: var(--pj-ink); margin-bottom: 18px; }
|
||||
|
||||
/* 세로 막대(섹션별/담당자별 공용) */
|
||||
@@ -1676,13 +1797,15 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
.pj-dash-tooltip b { font-size: 13.5px; margin-right: 6px; }
|
||||
.pj-dash-tooltip span { color: #cfd3da; }
|
||||
|
||||
/* 카드 등장 트랜지션 — 대시보드 탭을 열 때마다 살짝 떠오르며 나타난다. */
|
||||
.pj-dash-stat, .pj-dash-card { animation: pj-dash-in .35s cubic-bezier(.22,.9,.3,1) both; }
|
||||
/* 카드 등장 트랜지션 — 대시보드 탭을 열 때만(.pj-dash-intro) 살짝 떠오르며 나타난다.
|
||||
업무 창 닫기·저장·갱신으로 다시 그릴 때는 없음 — 매번 투명했다 나타나 깜박였다(2026-10-13). */
|
||||
.pj-dash-intro .pj-dash-stat, .pj-dash-intro .pj-dash-card { animation: pj-dash-in .35s cubic-bezier(.22,.9,.3,1) both; }
|
||||
.pj-dash-stats .pj-dash-stat:nth-child(2) { animation-delay: .04s; }
|
||||
.pj-dash-stats .pj-dash-stat:nth-child(3) { animation-delay: .08s; }
|
||||
.pj-dash-stats .pj-dash-stat:nth-child(4) { animation-delay: .12s; }
|
||||
.pj-dash-charts .pj-dash-card:nth-child(2) { animation-delay: .06s; }
|
||||
.pj-dash-charts .pj-dash-card:nth-child(3) { animation-delay: .12s; }
|
||||
.pj-dash-charts .pj-dash-card:nth-child(4) { animation-delay: .18s; }
|
||||
@keyframes pj-dash-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
|
||||
@media (max-width: 900px) { .pj-dash-stats { grid-template-columns: repeat(2, 1fr); } }
|
||||
|
||||
@@ -1914,6 +2037,8 @@ html.pj-embed .pj-btn-goto-project { display: inline-flex; align-items: center;
|
||||
transform: translateX(100%); transition: transform .22s ease;
|
||||
}
|
||||
.pj-inbox-panel.is-open { transform: translateX(0); }
|
||||
/* 내 업무 — 오른쪽 업무 창에 연 줄 */
|
||||
.pj-mtk-row.is-panel-selected > td { background: var(--pj-accent-tint); }
|
||||
.pj-inbox-panel iframe { display: block; width: 100%; height: 100%; border: 0; }
|
||||
.pj-inbox-item.is-selected { border-color: var(--pj-accent, #4573d2); box-shadow: 0 0 0 1px var(--pj-accent, #4573d2) inset; }
|
||||
|
||||
@@ -2475,6 +2600,9 @@ html.pj-goal-moving, html.pj-goal-moving * { cursor: grabbing !important; user-s
|
||||
@keyframes pj-goal-merge-flash { from { box-shadow: inset 0 0 0 2px var(--pj-accent), inset 0 0 0 999px rgba(123, 104, 238, .14); }
|
||||
to { box-shadow: inset 0 0 0 2px transparent, inset 0 0 0 999px rgba(123, 104, 238, 0); } }
|
||||
@media (prefers-reduced-motion: reduce) { .pj-goal-table tr.is-new-row > *, .pj-goal-table td.is-merge-flash { animation: none; } }
|
||||
/* 주간 회의록 — 줄을 그 자리에서 다시 그린 뒤(refreshMeeting) 새 줄 잠깐 강조(연간 목표와 같은 색) */
|
||||
.pj-meet-table tr.is-new-row > * { animation: pj-goal-row-new 1.4s ease-out; }
|
||||
@media (prefers-reduced-motion: reduce) { .pj-meet-table tr.is-new-row > * { animation: none; } }
|
||||
/* 칸 병합 — 끌어서 고르는 동안 글 선택 막기 */
|
||||
html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; cursor: cell !important; }
|
||||
/* 칸 아무 곳이나 눌러 입력 — 칸 전체가 글 입력 커서(관리자 화면) */
|
||||
@@ -2549,11 +2677,13 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
}
|
||||
.pj-ctxmenu-ic .pj-meet-quick-face { width: 20px; height: 20px; }
|
||||
.pj-member-pick.is-owner { opacity: .75; }
|
||||
.pj-meet-quick-table th:nth-child(1) { width: 30%; }
|
||||
.pj-meet-quick-table th:nth-child(2) { width: 17%; }
|
||||
.pj-meet-quick-table th:nth-child(3) { width: 19%; }
|
||||
.pj-meet-quick-table th:nth-child(4) { width: 15%; }
|
||||
.pj-meet-quick-table th:nth-child(5) { width: 19%; }
|
||||
/* 제목·담당자·프로젝트·섹션·작업(세부 작업으로 넣을 작업)·버튼 */
|
||||
.pj-meet-quick-table th:nth-child(1) { width: 24%; }
|
||||
.pj-meet-quick-table th:nth-child(2) { width: 15%; }
|
||||
.pj-meet-quick-table th:nth-child(3) { width: 15%; }
|
||||
.pj-meet-quick-table th:nth-child(4) { width: 12%; }
|
||||
.pj-meet-quick-table th:nth-child(5) { width: 15%; }
|
||||
.pj-meet-quick-table th:nth-child(6) { width: 19%; }
|
||||
.pj-meet-quick-acts { white-space: nowrap; text-align: right; }
|
||||
.pj-meet-quick-del {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 4px; vertical-align: middle;
|
||||
@@ -2573,8 +2703,12 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
.pj-meet-pick-cell:hover { border-color: #cfd4da; background: #fafbfc; }
|
||||
.pj-meet-quick-apply { height: 26px; padding: 0 10px; border: none; border-radius: 6px; background: var(--pj-accent); color: #fff; font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; }
|
||||
.pj-meet-quick-apply:disabled { opacity: .5; cursor: default; }
|
||||
.pj-meet-quick-done { display: inline-flex; align-items: center; gap: 4px; font-size: 11.5px; color: #1f8a4c; white-space: nowrap; }
|
||||
.pj-meet-quick-done a { color: inherit; }
|
||||
.pj-meet-quick-actbox { display: flex; align-items: center; justify-content: flex-end; gap: 2px; flex-wrap: nowrap; } /* 체크·휴지통(또는 적용·×) 가로 한 줄 */
|
||||
.pj-meet-quick-actbox .pj-meet-quick-del { margin-left: 0; }
|
||||
.pj-meet-quick-done { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; flex: none; border-radius: 6px; color: #1f8a4c; text-decoration: none; }
|
||||
.pj-meet-quick-done .material-symbols-outlined { font-size: 18px; }
|
||||
a.pj-meet-quick-done:hover { background: #e8f5ee; }
|
||||
.pj-meet-quick-done.is-gone { color: #9aa1ab; }
|
||||
.pj-meet-quick-table tr.is-done input, .pj-meet-quick-table tr.is-done .pj-meet-pick-cell { color: var(--pj-ink-soft); pointer-events: none; }
|
||||
.pj-meet-quick-table tr.is-done .pj-meet-pick-cell.is-person { color: var(--pj-ink-soft); }
|
||||
.pj-meet-quick-add { margin-top: 4px; padding: 2px 6px; border: none; background: none; color: var(--pj-accent-dark); font: inherit; font-size: 12px; cursor: pointer; }
|
||||
@@ -2811,6 +2945,8 @@ th.pj-meet-c-label { position: relative; font-weight: 600; color: #3b4048; text-
|
||||
.pj-meet-more { position: absolute; top: 3px; right: 2px; width: 24px; height: 24px; opacity: 0; transition: opacity .12s; }
|
||||
.pj-meet-more .material-symbols-outlined { font-size: 18px; }
|
||||
th.pj-meet-c-label:hover .pj-meet-more, .pj-meet-more:focus { opacity: 1; }
|
||||
/* 구분(구역) 칸 ⋮ — 구역 위로·아래로(줄 메뉴와 같은 모양) */
|
||||
th.pj-meet-c-sec:hover .pj-meet-sec-more { opacity: 1; }
|
||||
textarea.pj-meet-text, textarea.pj-meet-rnote, .pj-meet-notes textarea {
|
||||
display: block; width: 100%; box-sizing: border-box; min-height: 38px; padding: 6px; border: none; background: transparent;
|
||||
font: inherit; line-height: var(--pj-text-leading); color: inherit; resize: none; overflow: hidden;
|
||||
@@ -3052,3 +3188,23 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p
|
||||
}
|
||||
.pj-desc-stylepop button:hover { background: #f1f2f4; }
|
||||
.pj-desc-colorchip { display: inline-block; width: 22px; text-align: center; font-weight: 700; font-size: 15px; }
|
||||
/* 회의록 작업 등록 — 제목 앞 주차(N주차 작업 등록, 주차마다 따로 기억) */
|
||||
.pj-meet-quick-week { color: var(--pj-accent); }
|
||||
.pj-meet-quick-note { padding: 10px 8px; color: #8a9099; font-size: 12.5px; }
|
||||
/* 작업 등록 — [크게 열기] 창(같은 표를 옮겨 쓴다)·등록된 제목(누르면 오른쪽 작업 창) */
|
||||
.pj-meet-quick h3 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
|
||||
.pj-meet-quick-expand { margin-left: auto; order: 2; display: inline-flex; align-items: center; gap: 3px; }
|
||||
.pj-meet-quick-expand .material-symbols-outlined { font-size: 15px; }
|
||||
.pj-meet-quick-open { display: block; width: 100%; padding: 2px 6px; border: none; background: none; text-align: left; font: inherit;
|
||||
color: var(--pj-ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; border-radius: 5px; }
|
||||
button.pj-meet-quick-open:hover { background: #f1f3f5; color: var(--pj-accent-dark, #2f5bb7); text-decoration: underline; }
|
||||
.pj-meet-quick-open.is-plain { cursor: default; color: var(--pj-ink-soft); }
|
||||
.pj-meet-quick-inherit { display: block; padding: 0 4px; color: #9aa1a9; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; }
|
||||
.pj-meet-quick-modal { position: fixed; inset: 0; z-index: 2100; /* 고르기 메뉴(.pj-ctxmenu 2200)가 그 위에 */ display: flex; align-items: center; justify-content: center;
|
||||
padding: 16px; box-sizing: border-box; background: rgba(15, 17, 21, .4); }
|
||||
.pj-meet-quick-modal-card { width: min(1100px, 96vw); max-height: 88vh; overflow: auto; box-sizing: border-box; padding: 14px 18px 18px;
|
||||
border-radius: 12px; background: #fff; box-shadow: 0 18px 50px rgba(0, 0, 0, .3); }
|
||||
.pj-meet-quick-modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
|
||||
.pj-meet-quick-modal-head h3 { margin: 0; font-size: 16px; font-weight: 800; }
|
||||
.pj-meet-quick-modal .pj-meet-quick-table { font-size: 14px; }
|
||||
.pj-meet-quick-modal .pj-meet-quick-table th { font-size: 13px; padding: 6px 8px; }
|
||||
|
||||
+1422
-287
File diff suppressed because it is too large
Load Diff
@@ -340,5 +340,10 @@
|
||||
: `총 ${tbody.querySelectorAll("tr").length}명`;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
{# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #}
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<script src="/static/erp-notice.js?v=20261012a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
<script src="/static/erp-overdue.js?v=20261014b" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<link rel="stylesheet" href="/static/erp-shell.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-attach-viewer.css" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
</head>
|
||||
<body class="erp-body erp-app-body">
|
||||
@@ -95,6 +97,16 @@
|
||||
</span>
|
||||
<span class="erp-sidebar-label">업무 모듈</span>
|
||||
</a>
|
||||
{# 긴급 공지 관리 — 수퍼관리자만(app/modules/notice) #}
|
||||
<a class="erp-sidebar-item" href="/notice/" title="정한 시각에 받는 사람 화면 가운데에 띄우는 공지">
|
||||
<span class="erp-sidebar-icon">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 11v2a1 1 0 0 0 1 1h2l5 4V6L6 10H4a1 1 0 0 0-1 1Z"/><path d="M15 9a4 4 0 0 1 0 6"/><path d="M18 6a8 8 0 0 1 0 12"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="erp-sidebar-label">긴급 공지</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if is_admin %}
|
||||
<a class="erp-sidebar-item" href="/admin">
|
||||
@@ -179,6 +191,10 @@
|
||||
인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #}
|
||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||
<script src="/static/erp-attach-viewer.js" defer></script>
|
||||
{# 긴급 공지 — 로그인한 모든 화면 가운데(받는 사람이 [확인] 전까지). app/modules/notice #}
|
||||
{% if user %}<script src="/static/erp-notice.js?v=20261012a" defer></script>{% endif %}
|
||||
{# 마감 지난 내 업무 — 로그인한 모든 화면 위쪽(닫으면 1시간 뒤 다시). Project 권한이 없으면 조용히 멈춘다. #}
|
||||
{% if user %}<script src="/static/erp-overdue.js?v=20261014b" defer></script>{% endif %}
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -167,5 +167,10 @@
|
||||
refreshHealth();
|
||||
setInterval(refreshHealth, 30000);
|
||||
</script>
|
||||
</body>
|
||||
{# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #}
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<script src="/static/erp-notice.js?v=20261012a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
<script src="/static/erp-overdue.js?v=20261014b" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace DbxNotifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 큰 알림 창 — 웹 프로젝트 화면의 큰 팝업(.pj-alert-pop)과 같은 모양: 흰 카드·둥근 모서리 16·연분홍 머리(종 + "새 알림 N건" + 닫기)·
|
||||
/// 줄마다 배지(작업 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛.
|
||||
/// 줄마다 배지(업무 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛.
|
||||
/// 다른 프로그램 위(맨 위)에 뜨지만 포커스는 빼앗지 않는다(입력 중이던 창 그대로). 둥근 모서리·그림자를 위해
|
||||
/// 픽셀 단위 투명 창(UpdateLayeredWindow)으로 직접 그린다.
|
||||
/// </summary>
|
||||
@@ -227,7 +227,7 @@ namespace DbxNotifier
|
||||
float s = _s;
|
||||
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
|
||||
|
||||
string kind = a.IsMention ? "나를 태그" : "작업 배정";
|
||||
string kind = a.IsMention ? "나를 태그" : "업무 배정";
|
||||
SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic);
|
||||
var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s);
|
||||
Fill(g, kr, 11 * s, a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec"));
|
||||
|
||||
@@ -21,12 +21,12 @@ namespace DbxNotifier
|
||||
|
||||
public bool IsMention => Type == "mention";
|
||||
|
||||
/// <summary>제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
|
||||
/// <summary>제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
|
||||
public string CleanTitle
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
|
||||
foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:" })
|
||||
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
|
||||
return Title;
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace DbxNotifier
|
||||
|
||||
Controls.Add(new Label
|
||||
{
|
||||
Text = "이 PC 에 ERP 알림(나를 태그·작업 배정)을 띄우려면\n내 ERP 계정에 연결하세요.",
|
||||
Text = "이 PC 에 ERP 알림(나를 태그·업무 배정)을 띄우려면\n내 ERP 계정에 연결하세요.",
|
||||
Location = new Point(20, 18), AutoSize = true, MaximumSize = new Size(400, 0),
|
||||
});
|
||||
Controls.Add(new Label { Text = "ERP 주소", Location = new Point(20, 84), AutoSize = true });
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<Company>DBX</Company>
|
||||
<Product>DBX 알림</Product>
|
||||
<AssemblyTitle>DBX 알림</AssemblyTitle>
|
||||
<Description>DBX ERP 프로젝트 알림(태그·작업 배정)을 화면에 띄우는 트레이 프로그램</Description>
|
||||
<Description>DBX ERP 프로젝트 알림(태그·업무 배정)을 화면에 띄우는 트레이 프로그램</Description>
|
||||
<Copyright>© 2026 DBX</Copyright>
|
||||
<NeutralLanguage>ko-KR</NeutralLanguage>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -10,7 +10,7 @@ using Microsoft.Win32;
|
||||
namespace DbxNotifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창.
|
||||
/// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·업무 배정 알림이 있으면 큰 알림 창.
|
||||
/// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로,
|
||||
/// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다.
|
||||
/// </summary>
|
||||
@@ -112,7 +112,7 @@ namespace DbxNotifier
|
||||
{
|
||||
Apply(r.Alerts);
|
||||
}
|
||||
if (manual && _pending.Count == 0) Balloon("새 알림 없음", "확인하지 않은 태그·작업 배정 알림이 없습니다.");
|
||||
if (manual && _pending.Count == 0) Balloon("새 알림 없음", "확인하지 않은 태그·업무 배정 알림이 없습니다.");
|
||||
}
|
||||
catch (ApiException ex) when (ex.Status == 401)
|
||||
{
|
||||
@@ -234,7 +234,7 @@ namespace DbxNotifier
|
||||
_cfg.Save();
|
||||
AutoStart.Set(c.AutoStartChecked);
|
||||
_timer.Start();
|
||||
Balloon("DBX 알림이 연결되었습니다", c.Email + " 님의 태그·작업 배정 알림을 이 PC 화면에 띄웁니다.");
|
||||
Balloon("DBX 알림이 연결되었습니다", c.Email + " 님의 태그·업무 배정 알림을 이 PC 화면에 띄웁니다.");
|
||||
_ = Poll(false);
|
||||
};
|
||||
_connect.Show();
|
||||
|
||||
@@ -125,6 +125,128 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
|
||||
|
||||
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
|
||||
|
||||
## 주간 회의록 항목 칸 묶음 마이그레이션 (027)
|
||||
|
||||
027은 `goal_meeting_items.label_cont` 열만 추가한다(기본 false, 기존 값 그대로, 다시 실행 가능). 미적용이면 "주요 업무" 칸의
|
||||
같은 항목 칸 줄 추가·항목 칸 나누기만 503 안내, 나머지는 그대로.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_027_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_027_meeting_label_groups.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT column_name FROM information_schema.columns WHERE table_name='goal_meeting_items' AND column_name='label_cont';"
|
||||
```
|
||||
|
||||
## 담당자·협업자 겹침 정리 마이그레이션 (028)
|
||||
|
||||
028은 스키마를 바꾸지 않고, 담당자와 같은 사람인 협업자 행(`task_followers`)만 지운다(담당자는 협업자가 아니다 — 2026-10-13).
|
||||
다시 실행해도 같고, 지운 행 수를 NOTICE 로 보여 준다. 앱은 새 코드부터 담당자를 협업자로 넣지 않으므로, 028 을 늦게 적용해도
|
||||
새로 겹치는 행은 생기지 않는다(예전 겹친 행만 남음). 되돌리기 = 아래 백업에서 task_followers 만 복원.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_028_$(date +%Y%m%d%H%M).sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT COUNT(*) FROM task_followers f JOIN tasks t ON t.id = f.task_id WHERE COALESCE(t.assignee_email,'') <> '' AND lower(f.user_email) = lower(t.assignee_email);"
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_028_followers_exclude_assignee.sql
|
||||
```
|
||||
|
||||
## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002)
|
||||
|
||||
002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를
|
||||
카페24·네이버·쿠팡·토스·GS샵·11번가·오늘의집·G마켓·카카오·롯데ON 으로 바꾼다(기존 매출·인증정보 그대로, 다시 실행 가능).
|
||||
미적용이면 수동 입력 토글·저장만 503 안내, 나머지 실적 화면은 그대로 동작한다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_002_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_002_manual_sales.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "SELECT code, sort_order, manual_input FROM perf_marketplaces ORDER BY sort_order;"
|
||||
```
|
||||
|
||||
## 실적 쇼핑몰 순서·신규 수동 입력 쇼핑몰 마이그레이션 (performance_db 003)
|
||||
|
||||
003은 기존 `쿠팡` 이름을 `쿠팡(윙)` 으로 바꾸고, 수동 입력 전용 쇼핑몰 `쿠팡(로켓)`(`coupang_rocket`)·`애터미아자몰`(`atomy`)을
|
||||
`manual_input = TRUE` 로 추가하며, 순서를 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 로
|
||||
바꾼다(기존 매출·인증정보 그대로, 다시 실행 가능). 002 뒤에 적용한다. 미적용이면 새 쇼핑몰 2곳만 화면에 안 나온다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_003_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_003_marketplace_order.sql
|
||||
```
|
||||
|
||||
## 실적 네이버 이름 마이그레이션 (performance_db 004)
|
||||
|
||||
004는 `perf_marketplaces` 의 `naver` 이름만 `네이버 스마트스토어` → `네이버` 로 바꾼다(다시 실행 가능). 미적용이면 설정 화면에 예전 이름이 남는다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_004_naver_name.sql
|
||||
```
|
||||
|
||||
## 실적 광고비 마이그레이션 (performance_db 005)
|
||||
|
||||
005는 광고비 표 `perf_ad_spend` 하나만 만든다(기존 표·데이터 그대로, 다시 실행 가능). 미적용이면 광고비 탭에 안내가 나오고 입력·업로드가 503.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_005_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_005_ad_spend.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
|
||||
```
|
||||
|
||||
되돌리기(광고비 데이터만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_spend;"`
|
||||
|
||||
## 실적 광고비 ROAS·보고서 항목 마이그레이션 (performance_db 006)
|
||||
|
||||
006은 `perf_ad_spend` 에 `roas`·`metrics` 열 두 개만 더한다(기존 값 그대로, 다시 실행 가능). 005 다음에 적용한다.
|
||||
미적용이면 네이버 보고서 업로드·네이버 일자별 상세만 503 안내, 나머지 광고비 화면은 그대로.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_006_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_006_ad_roas_metrics.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
|
||||
```
|
||||
|
||||
되돌리기(보고서 ROAS·상세만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas;"`
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
|
||||
|
||||
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_026_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_026_meeting_quick_parent_task.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT column_name FROM information_schema.columns WHERE table_name='goal_meeting_tasks' AND column_name='parent_task_id';"
|
||||
```
|
||||
|
||||
## 회의록 작업 등록 표 마이그레이션 (025)
|
||||
|
||||
025는 `goal_meeting_tasks` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 작업 등록 표를 주차별로 서버에 두어 모두가 같이 본다.
|
||||
미적용이면 표 자리에 "마이그레이션 025 필요" 안내만 나오고(브라우저에 남은 예전 표는 지우지 않고 기다린다), 회의록 다른 기능은 그대로.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_025_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_025_meeting_quick_tasks.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('goal_meeting_tasks') AS t;"
|
||||
```
|
||||
|
||||
## 긴급 공지 마이그레이션 (024)
|
||||
|
||||
024는 `urgent_notices`·`urgent_notice_targets`·`urgent_notice_acks`·`urgent_notice_images` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능).
|
||||
새 환경변수 없음(`PROJECT_DB_URL` 연결 풀을 같이 씀). 미적용이면 `/notice/` 는 "준비 필요" 안내, 공지 API 는 503, 화면 스크립트는 조용히 멈춘다.
|
||||
상세는 `docs/NOTICE_MODULE.md`.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_024_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_024_urgent_notices.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('urgent_notices') AS t;"
|
||||
```
|
||||
|
||||
## PC 알림 프로그램 마이그레이션 (023)
|
||||
|
||||
023은 `notifier_links`·`notifier_tokens` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 `/project/notifier` 화면은
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 긴급 공지 — `app/modules/notice/` (2026-10-12)
|
||||
|
||||
수퍼관리자가 만든 공지를 **정한 시각**에, **전체 또는 고른 사람**의 ERP 화면 **가로·세로 정가운데**에 띄운다.
|
||||
받는 사람이 **[확인]을 누를 때까지** 화면을 열 때마다 다시 뜬다(알림 팝업과 달리 닫기·Esc·바깥 클릭으로 안 닫힘).
|
||||
|
||||
## 권한
|
||||
|
||||
| 할 일 | 누가 |
|
||||
| --- | --- |
|
||||
| 공지 만들기·고치기·취소·이미지 올리기·확인 현황(`/notice/`) | 수퍼관리자(`SUPER_ADMIN_EMAIL`)만 — Admin 도 안 됨 |
|
||||
| 공지 받기·[확인] | 로그인한 등록 사용자(모듈 권한과 무관) — 전체 공지면 모두, 아니면 고른 사람만 |
|
||||
| 본문 이미지 보기(`/notice/images/{id}`) | 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난, 취소 안 된 공지) |
|
||||
|
||||
들어가는 곳: ERP 왼쪽 아래 **긴급 공지**(수퍼관리자만 보임), Project 화면 오른쪽 위 ⚙(Project 옵션) 안 **긴급 공지 만들기·관리**.
|
||||
|
||||
## 화면
|
||||
|
||||
- **관리(`/notice/`)** — 프로젝트 화면 부품을 그대로 쓴다(`project.js` 를 `window.PJ_LIB_ONLY` 로 불러 `window.PJLib` 만 —
|
||||
프로젝트 알림 팝업·실시간 동기화 등은 이 화면에서 돌지 않는다):
|
||||
· **내용** = 작업 설명란과 같은 편집기(`createDescEditor`, 서식 도구 `project/_desc_fmtbar.html` 공용 — 굵게·기울임·밑줄·취소선·
|
||||
글자 색/크기·글머리/번호 목록·체크리스트·인용·링크·서식 지우기·이미지 버튼/붙여넣기·크기 조절·더블클릭 크게 보기). @태그만 뺐다
|
||||
(공지는 작업이 아니라 수신함에 쌓일 곳이 없다). 이미지는 `/notice/api/images` 로 올린다.
|
||||
· **띄울 날짜** = 프로젝트 날짜 팝업(`enhanceDateInput` — 일요일·공휴일 빨강·오늘·지우기), 시각은 옆 칸(5분 단위). 날짜를 비우면 바로.
|
||||
· **받는 사람** = 전체 / 고른 사람 — 프로젝트 멤버 고르기와 같은 아이콘 + 이름 + 체크(`memberPickHtml`, 등록 사용자 전원).
|
||||
· [미리 보기](받는 사람 화면과 같은 모양). 목록 = 상태(예약 · 표시 중 · 취소됨) · 받는 사람 · 확인 현황(확인한 사람·시각, 아직 안 한 사람).
|
||||
[고치기]([이미 확인한 사람에게도 다시 띄우기] 선택 가능) · [취소](더 띄우지 않음, 기록은 남음) · [취소 되돌리기].
|
||||
- **표시(`static/erp-notice.js`)** — `erp_base.html` 을 쓰는 모든 화면 + 업무 모듈 첫 화면(`main.html`)·관리자 페이지(`admin.html`). 본문 서식(목록·체크리스트·인용)은
|
||||
`erp-notice.css` 가 작업 설명란과 같게 그린다(프로젝트 밖 화면에서도).
|
||||
`GET /notice/api/pending` 을 열 때·30초마다·창을 다시 볼 때 확인(띄울 시각 정밀도 ≈30초). 여러 건이면 오래된 것부터 차례대로(1/3).
|
||||
`document.body` 에 붙여 화면 배율(`.erp-app` zoom)과 무관하게 정가운데. [확인] 저장이 실패하면 창을 그대로 두고 알린다. 다른 탭·다른
|
||||
곳에서 확인·취소되면 다음 확인 때 닫힌다(같은 브라우저 다른 탭은 localStorage 신호로 바로). iframe(수신함 오른쪽 작업 창) 안에선 안 돈다.
|
||||
024 미적용(503)·로그아웃(401)이면 조용히 멈춘다.
|
||||
|
||||
## 저장 — project_db 마이그레이션 024 (`scripts/sql/project_db_024_urgent_notices.sql`)
|
||||
|
||||
| 표 | 용도 |
|
||||
| --- | --- |
|
||||
| `urgent_notices` | 제목·본문 HTML(서버 정리)·`show_at`·`to_all`·만든/고친 사람·`cancelled_at` |
|
||||
| `urgent_notice_targets` | 받는 사람(`to_all = FALSE` 일 때) |
|
||||
| `urgent_notice_acks` | [확인] 기록(한 사람 한 번, 시각) |
|
||||
| `urgent_notice_images` | 본문 이미지(bytea, png·jpeg·gif·webp 10MB 이하 — 파일 앞 바이트로 형식 판단, svg·html 거절) |
|
||||
|
||||
- 연결 풀은 프로젝트 저장소(`PROJECT_DB_URL`)와 같이 쓴다(`ProjectStore.pool`). 새 환경변수 없음.
|
||||
- 본문은 작업 설명란과 같은 허용 목록으로 정리한 뒤 이미지는 `/notice/images/{id}` 만 남긴다(외부 주소·data: 이미지 제거).
|
||||
- 이미지는 올릴 때 공지 없이(`notice_id NULL`) 저장 → 공지 저장 때 본문에 든 **내가 올린** 이미지만 그 공지에 묶는다. 하루 넘게 안 묶인
|
||||
이미지는 다음 저장 때 지운다.
|
||||
- 이미지 응답: `nosniff` · `sandbox` CSP · `Cache-Control: private`.
|
||||
|
||||
## PC 알림 프로그램
|
||||
|
||||
아직 긴급 공지를 띄우지 않는다(웹만). 붙이려면 `desktop/notifier` 에 공지 창(가운데)·[확인] 호출을 추가하고 exe 를 다시 빌드해야 한다.
|
||||
|
||||
## 테스트
|
||||
|
||||
- `tests/test_notice.py` — 본문 정리·이미지 형식·시각(한국시간)·받는 사람 검증, API 권한(수퍼관리자만 관리·받는 사람만 확인/이미지·503). DB 없음.
|
||||
- `tests/test_notice_db.py` — 실제 PostgreSQL(로컬 테스트 DB): 예약 시각·고른 사람·확인 한 번·취소/되돌리기·고치기·다시 띄우기·남의 이미지 안 묶임.
|
||||
- `tests/js/notice_ui.test.js` — jsdom: 가운데 창·차례대로·Esc/바깥 클릭 무시·확인 실패 유지·다른 곳 확인 반영·503 멈춤.
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
|
||||
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑 = **구현됨**, 나머지 5개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑·쿠팡·카카오 = **구현됨**(쿠팡은 2026-10-12 — 매출 규칙은 WING 실데이터 대조 전, 카카오는 2026-10-13 — 판매자센터 대조 전), 나머지 3개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||
|
||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||
@@ -183,6 +183,65 @@
|
||||
+ 주문 상태별·클레임·정산 항목 합계. 화면 숫자와 다르면 출처별 열로 어느 쪽이 빠졌는지 본다.
|
||||
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||
|
||||
### 쿠팡 (`adapters/coupang.py`, 구현됨 — 규칙 대조 전)
|
||||
- **시간 초과 대응**(2026-10-13): 31일치 배송완료(FINAL_DELIVERY) 발주서처럼 건수가 많으면 쿠팡 게이트웨이가
|
||||
504 "Request timed out" 을 낸다. 502·503·504·응답 시간 초과(`GatewayTimeout`)면 그 구간을 반으로(31→15→7→3→1일) 줄여 다시 부르고,
|
||||
줄인 크기는 같은 상태의 다음 구간에도 쓴다(로켓그로스도 같은 방식). 하루 구간도 계속 시간 초과면 3·6초 쉬고 2번 더 부른 뒤 실패.
|
||||
오류 문구 끝에 실패한 구간·상태 `[주문일 …~…, 상태 …]` 를 붙인다.
|
||||
|
||||
- 맞출 화면(2026-10-12 사용자 지정): WING → 비즈니스 인사이트 → **판매분석**, 판매자배송 + 로켓그로스, 날짜 선택 → **매출(원)**.
|
||||
판매분석 자체를 주는 Open API 는 없다(developers.coupang.com API 목록 확인) → 주문 API 두 개를 **결제일(한국 시간)** 로 합친다.
|
||||
- 인증: Vendor ID + Access Key + Secret Key, 요청마다 CEA HMAC 서명. 키는 '자체개발' + 이 서버 IP 를 허용 IP 에.
|
||||
- 판매자배송: 발주서 목록(일단위 페이징) `/v5/vendors/{vendorId}/ordersheets` — 주문일(`createdAtFrom/To`, `yyyy-mm-dd+09:00`,
|
||||
31일까지) × 상태 6개(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING), 50건씩 `nextToken`. 주문일 하루 앞부터 불러
|
||||
`paidAt` 으로 다시 거른다. 줄 금액 = `orderPrice`(판매가 × 수량, 쿠폰 할인 전), 같은 발주서·줄은 한 번만. 결제 뒤 취소된 줄
|
||||
(`canceled`·`cancelCount`)도 결제일 매출(지난 날짜가 줄지 않게, 원본 확인에 따로). 완료 반품·결제 전 취소는 목록에 없다(쿠팡 안내).
|
||||
- 로켓그로스: `/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders?paidDateFrom=yyyymmdd&paidDateTo=` — 결제일, 30일까지, 분당 50회
|
||||
(호출 간격 1.25초), `paidAt` 은 밀리초. 줄 금액 = `unitSalesPrice × salesQuantity`. **출고된 주문만** 나온다(쿠팡 안내 — 오늘 주문은 늦게 잡힐 수 있음).
|
||||
- 사건: 주문 하나 = SALE(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), `replace_range`(접두어 `coupang:`).
|
||||
배송비는 매출 제외. 구매자·수령자·통관·배송 메모·직접 입력 항목은 저장·표시하지 않는다.
|
||||
- 원본 데이터 확인(쿠팡): 날짜별 **매출 후보** — ① 현재 규칙(판매자배송 판매가 + 로켓그로스) ② 판매자배송 판매가 ③ 할인 뒤
|
||||
④ 취소분 뺀 값 ⑤ 로켓그로스 + 판매량 — 를 WING 판매분석의 같은 날 "매출(원)"·"판매량" 과 비교해 규칙을 확정한다(`candidates_title`).
|
||||
로켓그로스만 거부돼도 판매자배송 결과는 보인다.
|
||||
|
||||
### 카카오 (`adapters/kakao.py`, 구현됨 — 판매자센터 대조 전, 2026-10-13)
|
||||
- 카카오쇼핑 Open API(shopping-developers.kakao.com). 주소 `https://kapi.kakao.com`, 모든 호출에 헤더 3개:
|
||||
`Authorization: KakaoAK {앱 어드민 키}`(카카오쇼핑 API 허락된 카카오디벨로퍼스 앱) ·
|
||||
`Target-Authorization: KakaoAK {판매자 API 인증키}`(판매자센터 → 정보관리 → 판매채널 정보 → API 인증키) ·
|
||||
`channel-ids: 101`(톡스토어, 선물하기 1, 둘 다 `1,101`). 입력칸 `admin_key`·`api_key`(처음 입력칸 이름 유지)·`channel_ids`(선택).
|
||||
두 키가 같은 앱이면 code -2, 판매자 키 무효면 -401, 앱-판매자 연결 전이면 "대행사 매핑/권한 확인" → 모두 인증 실패로 안내.
|
||||
Open API 는 카카오쇼핑 검토(“API 연동 검토 요청”)로 허락된 앱만 쓸 수 있다.
|
||||
- 수집: 결제일시 기준 주문내역 `GET /v2/shopping/orders/paidAt?from=&to=&size=100`(24시간까지 — 하루씩, 다음 쪽 `token`) →
|
||||
금액이 없어 결제된 주문마다 주문정보 `GET /v1/shopping/order?order_id=`(목록 `modifiedAt` 이 같으면 메모리 캐시 재사용).
|
||||
- 사건: 결제(`paymentId`) 하나 = SALE `kakao:{paymentId}`, 날짜 = 결제일. 금액 = 상품 줄마다
|
||||
`(productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice − adminDiscountPrice` 합, 배송비 제외.
|
||||
미결제(Created·PayRequest·PayWaiting·PayChecking·PayFailed·UnpaidCancelComplete)만 빼고 결제 뒤 취소·반품은 포함(네이버와 같은 기준).
|
||||
`replace_range`. 문서에 결제금액 항목이 없어 만든 식이라 **원본 데이터 확인의 항목 합계로 판매자센터 매출과 대조해 확정**한다.
|
||||
- 개인정보(`orderer`·`orderDeliveryRequest`·`orderTicketReceiver`, 클레임의 수거·교환 이름·주소·연락처·사유 글)는 받자마자 값을 지운다.
|
||||
|
||||
### 수동 입력(마이그레이션 002, 2026-10-12)
|
||||
|
||||
- 설정 → 쇼핑몰 표 **수동 입력** 토글(관리자, `perf_marketplaces.manual_input`, 기본 꺼짐). 켜면 실적 일자별 표에서 그 쇼핑몰의
|
||||
**오늘까지 날짜 칸**을 눌러 총매출을 입력한다(제목 ✎, 수동 값은 파란 숫자). Enter·Tab·↓ 저장 후 아래 칸, Shift+Enter·↑ 위 칸, Esc 취소,
|
||||
칸을 벗어나면 저장. 입력을 마치면 새로고침해 합계·수수료·그래프를 서버 계산으로 다시 그린다. 입력은 모듈 권한자 누구나
|
||||
(`PUT /performance/api/manual-sales/{code}/{day}`, `{amount}` — 비우면 지움, 쉼표·"원" 허용, ±1조 이내, 앞날·꺼진 쇼핑몰은 400).
|
||||
- 값은 `perf_manual_sales`(쇼핑몰 × 날짜 하나, `updated_by`). **넣은 날은 그 값이 API 수집값을 대신**하고(합산 아님), 넣지 않은 날은
|
||||
API 값. 대체는 `PerformanceDBStore.daily_amounts` 한 곳에서 해 실적 화면·회의록 머리 카드가 같은 숫자를 본다. 수수료는 그날 요율로 계산.
|
||||
토글을 끄면 값은 남지만 집계에 쓰지 않는다. 매출 업데이트(동기화)는 수동 값을 지우지 않는다.
|
||||
- 002 미적용: 읽기는 수동 값 없음으로 조용히 동작, 토글·저장은 503 안내.
|
||||
- 열 순서(003 + `registry.py`): 카페24 · 네이버 · 쿠팡(윙) · 쿠팡(로켓) · 오늘의집 · G마켓 · 카카오 · GS샵 · 11번가 · 롯데ON · 토스 · 애터미아자몰.
|
||||
기존 `coupang`(WING API) 이름은 `쿠팡(윙)`. `naver` 이름은 `네이버`(004, 예전 `네이버 스마트스토어`).
|
||||
- **수동 입력 전용 쇼핑몰**(003, `adapters/manual.py` — `manual_only = True`): `쿠팡(로켓)`(`coupang_rocket`)·`애터미아자몰`(`atomy`).
|
||||
API 가 없어 매출 업데이트(`sync_all`)에서 빠지고, 설정 화면에 인증 설정·연결 테스트 버튼이 없으며 연결 상태는 "수동 입력".
|
||||
수동 입력 토글은 늘 켜짐(화면 disabled, API 로 끄면 400). 매출은 일자별 표 날짜 칸에 직접 입력.
|
||||
- **수동 입력 엑셀 업로드**(`manual_upload.py`, 일자별 표 머리 [엑셀 업로드] → 팝업): 샘플 `GET /api/manual-sales/sample.xlsx`
|
||||
(모듈 폴더 `upload_sample.xlsx`), 업로드 `POST /api/manual-sales/upload`(모듈 권한자 누구나 — 날짜 칸 입력과 같은 권한).
|
||||
양식: 첫 시트 1행 머리글, 1열 날짜(엑셀 날짜·2026-10-12·2026.10.12·20261012), 2열부터 쇼핑몰 이름(설정 이름·짧은 이름·코드,
|
||||
띄어쓰기·대소문자 무시). 수동 입력이 켜진 쇼핑몰 열만, **값이 있는 칸만** 반영(같은 날 값 덮어씀, 빈 칸은 기존 값 그대로, 0 은 0원).
|
||||
꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 줌. 숫자 아님·날짜 못 읽음·앞으로의 날짜·같은 쇼핑몰+날짜 두 번이면
|
||||
**아무것도 저장하지 않고** 칸 위치(B3 등) 목록을 돌려준다. 저장은 한 트랜잭션(`set_manual_sales_bulk`). 5MB·2,000일 상한.
|
||||
- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`).
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
@@ -242,8 +301,15 @@
|
||||
|
||||
## 6. 동기화 (`sync.py`)
|
||||
|
||||
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
|
||||
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·자동 업데이트 공용. 기본 기간: 오늘 포함 최근
|
||||
`PERFORMANCE_SYNC_DAYS`(기본 7)일.
|
||||
- **자동 업데이트**(`auto_sync.py`, 2026-10-13): 웹 프로세스 시작 때 데몬 스레드(`main._lifespan`) — 매일 **09:00~19:00(KST)
|
||||
정각·30분마다**(하루 21회) **오늘 포함 최근 10일**을 [매출 업데이트]와 같은 방식(진행 창 작업 `jobs`, `trigger='schedule'`(DB CHECK 허용값),
|
||||
사용자 "자동 업데이트")으로 다시 가져온다. 그 시각에 다른 업데이트가 돌고 있으면 그 회차는 건너뜀, 30분을 넘긴 회차 뒤엔
|
||||
밀린 회차를 몰아서 돌리지 않고 다음 회차부터, 서버 시작 시각 회차는 돌리지 않음. 자동 업데이트 중 누가 버튼을 누르면 그 진행
|
||||
창을 같이 본다(취소는 관리자). 수동 입력 전용 쇼핑몰은 대상 아님. env `PERFORMANCE_AUTO_SYNC`(false=끄기)·
|
||||
`PERFORMANCE_AUTO_SYNC_DAYS`(10)·`PERFORMANCE_AUTO_SYNC_HOURS`(9-19). uvicorn 단일 워커 기준(여러 프로세스면 회차마다 겹쳐
|
||||
돌지만 같은 쇼핑몰 동시 실행은 DB 에서 막힘).
|
||||
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
|
||||
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
|
||||
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
|
||||
@@ -273,6 +339,33 @@
|
||||
|
||||
## 7. 화면
|
||||
|
||||
- **탭**(2026-10-13): 왼쪽 위 큰 탭 둘 — [매출 실적](검정, `/performance/`) · [광고비](주황, `/performance/ads`) — 아이콘 + 고른 탭 색으로 구분,
|
||||
설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols `settings`, `/performance/settings`). `_tabs.html`.
|
||||
- **광고비** `/performance/ads?period=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널,
|
||||
연간은 월)·일별 추이·채널 비중·월/연 누적. 채널(2026-10-14) = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰
|
||||
(`ad_spend.CHANNELS`, 앱이 정함 — 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같고 쿠팡(윙)만 `coupang_wing`).
|
||||
모든 칸 직접 입력 가능, 칸 표시 = **광고비(ROAS%)** — ROAS = 그 칸 기간의 매출 실적 총매출 ÷ 광고비 × 100(정수 반올림,
|
||||
`ad_spend.roas`). 매출 쇼핑몰 = `ROAS_SALES_CODE`(같은 쇼핑몰, 쿠팡(윙) = `coupang`). **구글·메타·네이버는 ROAS 계산 안 함**(`FILE_ROAS` — 광고 보고서의 ROAS 값, `perf_ad_spend.roas`, 마이그레이션 006;
|
||||
여러 날 = Σ(그날 ROAS × 광고비) ÷ Σ광고비, 광고비 0 인 날 제외 — `file_roas`),
|
||||
합계 열·월/연 누적 = 매출 실적에 들어가는 쇼핑몰 전체 매출. 광고비가 없는 칸은 ROAS 없음. 광고비를 고치면 옛 ROAS 는 지우고 새로고침 때 다시 계산.
|
||||
KPI: 기간 광고비(전기간 대비), 매출 대비 광고비(같은 기간 광고비 ÷ 매출 실적 총매출), 월·연 누적.
|
||||
저장 `perf_ad_spend`(마이그레이션 005 — 채널 × 날짜 하나에 금액, `source` manual/upload/api), 미적용이면 화면에 안내·API 503.
|
||||
- 날짜 칸을 눌러 직접 입력(`PUT /api/ad-spend/{channel}/{day}`, 비우면 지움, 오늘까지) — 파란 숫자. 매출 수동 입력과 같은 JS(`MANUAL_API`).
|
||||
- [파일 업로드](`POST /api/ad-spend/upload?channel=`) — 양식이 정해진 채널만(`ad_spend.PARSERS`). **여러 파일**을 한 번에(2026-10-14,
|
||||
`files` + 파일마다 `modified` = 브라우저 File.lastModified, 최대 30개) — 같은 날짜가 여러 파일에 있으면 **파일 날짜(수정 시각)가 최신인 파일** 값
|
||||
(같으면 나중 파일, `ad_spend.merge_results`), 오류는 `[파일 이름]` 을 붙여 모두 보여 주고 하나라도 있으면 전부 저장 안 함. 업로드가 끝나면 창을 닫고 새로고침. 파일에 있는 날만 덮어쓰고(주황 숫자),
|
||||
잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다. **쿠팡(윙)·쿠팡(로켓)**(같은 양식, 윙은 2026-10-14) = 쿠팡 광고 보고서 CSV(UTF-8/CP949)·엑셀:
|
||||
1열 날짜(`2026년 10월 01일`), 19열 청구금액(+부가가치세). **1열에 날짜가 있는 줄의 19열 값**(2026-10-14 — 윙 보고서는
|
||||
캠페인 줄에도 날짜가 있고 19열이 비어 있어 예전엔 "청구금액이 비어 있습니다" 로 막혔다): 19열이 빈 줄은 건너뛰고,
|
||||
같은 날짜에 값이 있는 줄이 여럿이면 더한다. "전체" 합계 줄·머리글·1열이 빈 캠페인 줄은 건너뜀. 날짜 줄은 있는데
|
||||
값이 한 줄도 없던 날은 넘어간다(응답 `empty_days` 에만, 창은 그대로 닫힘). 청구금액이 한 줄도 없는 파일도 오류 없이 넘어감
|
||||
(날짜 줄 자체가 없을 때만 양식 오류).
|
||||
- **네이버**(2026-10-14) = 네이버 광고 보고서 CSV·엑셀(하루 한 줄): 3열 기간(`2026.09.30.`), 4열 총비용 = 광고비,
|
||||
12열 구매완료 광고수익률(%) = 그날 ROAS(`roas`), 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은
|
||||
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
|
||||
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
|
||||
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
|
||||
- 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력.
|
||||
- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
|
||||
기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
|
||||
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
|
||||
|
||||
+148
-3
@@ -4,9 +4,9 @@
|
||||
> 보드로 관리하는 아사나(Asana) 스타일 협업 모듈. DB는 `project_db` 전용.
|
||||
|
||||
**화면 용어는 아사나 한국어판에 맞춘다(2026-09-25 통일)** — 새 화면·메시지도 이 표를 따른다.
|
||||
작업(예전 "업무") · 하위 작업 / 상위 작업 · 내 작업 · 섹션(예전 "세션"·"단계") ·
|
||||
**업무**(2026-10-13 다시 "작업" → "업무"로 통일 — 화면·메시지·알림 제목 모두, 6-16) · 세부 업무 / 상위 업무 · 메인 업무 · 내 업무 · 섹션(예전 "세션"·"단계") ·
|
||||
협업자(예전 "팔로워", 버튼은 "협업자로 참여 / 협업자에서 나가기" — 예전 "팔로우 / 팔로우 취소") ·
|
||||
목록(보기 탭, 예전 "리스트") · 캘린더(예전 "달력") · 수신함 · 첨부 파일 · 작업 링크 복사 ·
|
||||
목록(보기 탭, 예전 "리스트") · 캘린더(예전 "달력") · 수신함 · 첨부 파일 · 업무 링크 복사 ·
|
||||
프로젝트 칸 + "다른 프로젝트에 추가"(예전 "연결된 프로젝트") · 담당자 없음(예전 "(미지정)").
|
||||
"@태그"는 그대로 쓴다. 코드 식별자·DB 컬럼(`tasks`, `stage_id`, `task_followers` 등)과 코드 주석은 예전 이름 그대로다.
|
||||
**도움말** — `/project/help`(`project/help.html` + `static/project-help.css`·`static/project-help.js`), 프로젝트 관리 화면 상단 바 로그아웃
|
||||
@@ -290,9 +290,13 @@
|
||||
메인 작업(`scopeTasks()` 최상위, 중복 없이)과 하위 작업(화면 목록엔 없어 `GET /api/projects/{id}/subtasks-summary?scope=`
|
||||
— `db.list_subtasks_of`, 그 범위 메인 작업의 하위만, 하위 작업 자신의 담당자 기준)을 나눠 세고, 메인·하위·전체 완료 수와
|
||||
전체 완료율. 하위 요약은 15초 캐시(`paintWorkload`). **세로 막대**(같은 날 변경 — 사람마다 메인·하위 막대, 막대 = 그 작업 전체(100%),
|
||||
초록 채움 높이 = 완료율, 위 = 완료/전체·%. 처음엔 높이를 작업 수로 그려 많은 사람 기준에 다른 막대가 눌려 보였다 → 완료율로 수정). 막대를 누르면 오른쪽 슬라이드 패널(`openWorkloadDrawer`, body 에 붙음, z 950 — 편집 창 아래)에
|
||||
초록 채움 높이 = 완료율, 위 = 완료/전체·%, 이름 왼쪽 프로필 아이콘(`avatarHtml`, 사진 없으면 기본 사람 아이콘 — 2026-10-13). 처음엔 높이를 작업 수로 그려 많은 사람 기준에 다른 막대가 눌려 보였다 → 완료율로 수정). 막대를 누르면 오른쪽 슬라이드 패널(`openWorkloadDrawer`, body 에 붙음, z 950 — 편집 창 아래)에
|
||||
그 업무 목록(미완료·완료, 하위는 상위 작업 이름), 항목 → `openTaskById`(하위는 서버에서 받아) 편집 창. 편집 창이 닫히면
|
||||
요약을 다시 받아 대시보드·패널을 다시 그린다. 하위 요약 API 는 id·제목·마감일·완료 시각도 준다.
|
||||
**패널에서 연 편집 창은 패널 왼쪽에 붙어 열린다**(2026-10-13, `placeTaskBesideDrawer` — 패널은 그대로 보이고 다른 줄을 바로 누를 수 있음, 6-16).
|
||||
**다시 그릴 때 깜박임 없음**(2026-10-13) — 편집 창을 닫거나 저장·8초 갱신으로 대시보드를 다시 그려도 패널은 닫았다 다시 열지 않고
|
||||
내용만 바꾸며(`openWorkloadDrawer` 가 열린 패널 재사용 — 목록 스크롤·고른 줄 유지), 숫자·막대·도넛은 마지막 값(`dashPrev`/`dashFrom`)에서
|
||||
시작해 바뀐 것만 움직인다. 0부터 차오르는 애니메이션과 카드 등장(투명→보임, CSS `.pj-dash-intro`)은 대시보드 탭에 들어올 때만(`selectView` 가 `dashPrev` 비움). 카드 안 스크롤도 유지.
|
||||
- **보드** — 섹션별 칸반. `renderBoard` 는 캔버스를 통째로 다시 그리므로 **섹션 세로 스크롤(`.pj-col-body`,
|
||||
섹션 id/이름 기준)·보드 가로 스크롤을 저장했다가 되돌린다**(작업 창 닫기·완료 체크·8초 갱신 후에도 보던 자리).
|
||||
작업 창을 닫으면 펼친 카드의 하위 작업을 먼저 다 받은 뒤 한 번에 다시 그린다(짧아진 채 그리면 스크롤이 밀림). 섹션은 아사나처럼 **가로로 계속 늘어난다** — 화면을 넘치면
|
||||
@@ -512,6 +516,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
자동 배정도 일반 배정과 같이 활동이력·협업자·인앱 알림·메일이 나간다(`_newly_assigned`).
|
||||
멀티호밍으로 연결된 프로젝트 쪽 섹션 이동(`/links`)은 대상 아님.
|
||||
- 보드 섹션 머리 이름 옆에 기본 담당자 아바타(작게, 툴팁). 새 작업 팝업은 그 섹션 기본 담당자를 미리 채운다.
|
||||
**2026-10-13**: 편집 권한자는 보드·목록 섹션 제목 오른쪽 아이콘(없으면 점선 원)을 눌러 그 자리에서 기본 담당자를 고른다(6-16).
|
||||
- 009 미적용이어도 앱은 동작 — 조회는 `to_jsonb(행)->>'default_assignee_email'` 로 컬럼 유무와
|
||||
무관, 지정 시도만 503("마이그레이션 009 필요"). 화면은 기본 담당자가 바뀐 경우에만 필드를 보낸다.
|
||||
|
||||
@@ -561,6 +566,8 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
댓글 대화창은 말풍선 위 인용으로 답글 표시, 입력칸 위 "OO 님에게 답글" 줄.
|
||||
본문의 `@아이디` 는 사용자 목록(`/api/all-users`)과 맞으면 아이콘+이름 칩(`commentBodyHtml`).
|
||||
- 012 미적용이면 답글·반응 버튼이 숨겨지고, API 는 503 "마이그레이션 012 필요". 완료 이력·@칩은 012 없이도 동작.
|
||||
- **반응 알림**(2026-10-13): 반응을 켤 때(끌 때 X) 그 댓글을 쓴 사람에게 수신함 알림 `type=reaction`,
|
||||
제목 "내 댓글에 👍 반응: 업무 제목"(어떤 이모티콘인지), 본문 "프로젝트 · “댓글 앞부분”". 자기 댓글·지금 그 업무를 볼 수 없는 사람은 제외(`_notify_reaction`).
|
||||
|
||||
## 6-8. 수신함 오른쪽 작업 창 · 화면 배율
|
||||
|
||||
@@ -1079,6 +1086,7 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame
|
||||
- **전체 보기**: 프로젝트 화면 오른쪽 위 범위 토글(`#pj-scope-toggle`)은 숨기고, 왼쪽 메뉴 수신함 아래 **전체 보기**(Pro user 이상,
|
||||
`#pj-side-allview`) — 지금 프로젝트(없으면 목록 첫 활성 프로젝트) `/project/p/{id}?scope=all`. 프로젝트 화면에서는 새로고침 없이
|
||||
`applyAllScope(true)`. `?scope=all` 은 `data-is-pro` 일 때만 따른다. 이 프로젝트로 돌아가기 = 왼쪽 목록에서 프로젝트.
|
||||
**기본 보기는 대시보드**(2026-10-13 — 메뉴를 누르거나 `?scope=all` 로 들어오면 `selectView("dashboard")`, 달력 이전/다음 달 새로고침은 예전처럼 마지막 보기).
|
||||
- **수신함 작업 창**: [확인]으로 연 오른쪽 작업 창은 왼쪽 수신함 영역(`.pj-inbox-view`)을 누르면 닫힌다(메뉴·모달·알림 팝업 제외).
|
||||
- **설명란 글자 색·크기**: 서식 도구 [글자 색](10색, 기본)·[글자 크기](작게 12px·보통·크게 18px·더 크게 22px·제목 28px).
|
||||
`execCommand` 가 만든 `<font>` 를 바로 `<span style>` 로 바꾸고, 서버 `sanitize_description_html` 은 평범한 span 의 style 에서
|
||||
@@ -1191,9 +1199,146 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame
|
||||
잠근 트랜잭션 안에서 DB 연결을 더 빌리지 않음). 기본 담당자 지정도 같은 기준. 협업자 추가는 담당자 후보와 같은 `access.can_assign`
|
||||
(예전엔 관리자는 멤버가 아니어도 넣을 수 있었다).
|
||||
|
||||
- **회의록 구역 순서**(2026-10-12): 첫 열 "구분" 칸 우클릭·⋯ = 구역 위로·아래로·구역 끝에 줄 추가.
|
||||
`POST /api/goals/meeting-items/{item_id}/move-section {direction: -1|1}`(그 구역의 아무 줄) → `move_meeting_section` 이 회의록
|
||||
행 잠금 안에서 이어진 같은 구역 줄 묶음과 옆 묶음의 자리를 바꾼다(묶음 안 줄 순서·세로 병합 그대로, 맨 끝이면 그대로). 줄 이동과 같은
|
||||
권한(누구나, 회의 완료면 409). 다음 회의록은 `create_meeting` 이 이 순서를 이어받는다. 마이그레이션 없음.
|
||||
|
||||
- **회의록 항목 칸 묶음**(2026-10-12, 마이그레이션 027 `goal_meeting_items.label_cont`): "주요 업무" 칸 우클릭 → 위/아래 줄 추가는
|
||||
**항목 칸은 그대로 두고 그 항목 안에** 줄을 늘린다(`POST …/items {same_label: true}` — 이름을 묻지 않음. 아래 = 새 줄이 이어 붙고,
|
||||
묶음 첫 줄 위 = 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙음 — 연간 목표 016 과 같은 규칙). 주요 업무 칸 메뉴에 "줄 삭제"(그 한 줄).
|
||||
화면은 묶음 첫 줄 항목 칸 `rowspan`(`router._meeting_label_spans`, 구역 첫 줄은 늘 묶음 첫 줄), 이어 붙은 줄은 `tr[data-label-cont]`.
|
||||
항목 칸 메뉴(우클릭·⋯) = 따로 추가(묶음 맨 위·맨 아래 기준, 이름 물음) · 묶였으면 위로/아래로 대신 **항목 칸 나누기**
|
||||
(`POST /api/goals/meeting-items/{id}/split-label`) · 첫 줄 삭제(아래 줄이 이름을 이어받음). 묶인 줄의 순서 이동은 400.
|
||||
줄마다 주요 업무·정량 목표·연결키(line_key)는 따로라 지난주 리뷰는 줄 단위 그대로, 다음 주 회의록은 묶음을 이어받는다.
|
||||
027 미적용이면 같은 항목 칸 추가·나누기만 503, 나머지는 예전처럼.
|
||||
- **회의록 줄 작업 애니메이션**(2026-10-12): 줄 추가·삭제·이동·항목 칸 나누기·구역 이동·셀 병합/해제 뒤 새로고침 대신 `refreshMeeting` —
|
||||
같은 주소를 다시 받아 표의 구역(`tbody.pj-meet-sec`)만 바꿔 끼우고 저장·셀 도구(`PJMeetingCells.refresh`)·칸 순서(`pj-meet-rows` 이벤트)를
|
||||
다시 붙인다. 지운 줄은 흐려지며 사라지고, 남은 줄은 미끄러지고(FLIP), 새 줄은 내려오며 강조(연간 목표 `refreshTable` 과 같음).
|
||||
저장 안 된 글은 먼저 저장(실패면 작업 안 함), 계속 입력 중이면 저장 뒤 다시 그림, 받아 오기 실패면 새로고침. 줄 작업은 한 번에 하나씩.
|
||||
|
||||
- **회의록 작업 등록 — 새 프로젝트·새 섹션**(2026-10-12): 프로젝트 칸 목록 맨 위 "새 프로젝트"(Pro user 이상만 보임 — `POST /api/projects`,
|
||||
만든 사람이 소유자), 섹션 칸 맨 위 "새 섹션"(그 프로젝트 멤버 — `POST /api/projects/{id}/stages`). 이름만 묻고 만든 뒤 바로 그 칸에 고른다.
|
||||
- **회의록 작업 등록 — 고를 목록**(2026-10-12): 완료 프로젝트(`status = completed`)·완료 섹션(`is_done_stage`)은 목록에서 빼고,
|
||||
프로젝트를 고를 때 자동으로 넣는 섹션도 완료 섹션이 아닌 첫 섹션.
|
||||
- **회의록 작업 등록 — 주차별 서버 표**(2026-10-12, 마이그레이션 025 `goal_meeting_tasks`): 제목 "N주차 작업 등록"(`week_n`).
|
||||
예전엔 각자 브라우저(localStorage)에만 있어 다른 사람이 적거나 등록한 줄이 안 보였다 → 주차(`week_start`)마다 한 표를 서버에.
|
||||
API `GET/POST /api/goals/meetings/{주차}/quick-tasks` · `PUT/DELETE /api/goals/meeting-quick-tasks/{id}` ·
|
||||
`POST …/{id}/apply`(줄을 FOR UPDATE 로 잠그고 task_id 가 없을 때만 `_create_task_for` — 작업 창과 같은 권한·알림, 동시에 눌러도 하나).
|
||||
보기·고치기 = 회의록을 볼 수 있는 사람 누구나(회의 완료면 409), 줄에 고를 수 있는 프로젝트 = 내가 멤버인 것만(403),
|
||||
내가 멤버가 아닌 프로젝트를 가리키는 남의 줄은 프로젝트·섹션 이름·작업 링크를 가린다(`registered` 만). [적용] 뒤 줄은 고칠 수 없다.
|
||||
**작업 칸**(마이그레이션 026 `parent_task_id`): 프로젝트 → 섹션 → **작업** — 비우면 그 섹션에 새 작업, 이미 있는 작업을 고르면 [적용] 때
|
||||
그 작업의 세부 작업으로(섹션 없음). 후보 = 그 섹션(섹션이 없으면 프로젝트)의 미완료 메인 작업(`GET /api/projects/{id}/tasks`).
|
||||
서버는 고른 작업이 그 프로젝트 것인지 확인(400), 프로젝트를 바꾸면 섹션·작업을 비우고, [적용] 때 그 작업이 없어졌거나 옮겨졌으면 400.
|
||||
026 미적용이면 작업 칸 저장만 503(나머지 그대로). (025 의 `parent_id` — 잠깐 있던 '표 안 줄끼리 세부 작업' — 는 화면·API 에서 뺐다, 열은 남김.)
|
||||
**등록된 줄 제목 = 오른쪽 작업 창**: `/project/t/{id}?embed=1` 을 iframe 패널(`.pj-inbox-panel.pj-meet-task-panel`)에 — 수신함과 같이
|
||||
바꾸기·닫기(Esc·바깥 클릭·작업 창 닫기) 전에 `__pjEmbedSettle`(저장 대기 → 실패면 버리기/계속 편집), 닫으면 표를 다시 읽는다.
|
||||
**[크게 열기]** = 같은 표(DOM 그대로)를 넓은 창(`.pj-meet-quick-modal`, body 에, 고르기 메뉴 아래 z-index)으로 옮겨 쓰고 Esc·×로 제자리.
|
||||
화면은 빈 줄 3개를 화면에만 두고
|
||||
처음 채우는 순간 POST, 그 뒤 칸마다 PUT(줄마다 차례대로), 30초마다·창을 다시 볼 때 다시 읽는다(입력·저장 중엔 건너뜀).
|
||||
이 브라우저에 남은 예전 표(`pj_meet_quick:{이메일}:{주차}`, 이번 주면 `pj_meet_quick:{이메일}`)는 처음 열 때 서버로 옮기고 지운다.
|
||||
025 미적용이면 표 자리에 안내만(503).
|
||||
- **말풍선 위치**(`initHoverTips`, 2026-10-12): 늘 커서 위 — 위 여유가 적으면(화면 맨 위 회의록 머리 버튼 등) 꼬리 간격을 줄여(커서 8px 위)
|
||||
위에 두고, 그래도 안 들어갈 때만 아래로 뒤집되 마우스 화살표에 가리지 않게 커서 28px 아래. 예전엔 위 여백이 말풍선 높이+20px 보다
|
||||
작으면 커서 바로 아래(22px)로 뒤집혀 화살표가 글자를 가렸다.
|
||||
|
||||
정책 결정이 필요한 것(바꾸지 않음): 배정·완료 **메일**은 `PROJECT_NOTIFY_EMAIL`(없으면 Admin 전원)에게 프로젝트·작업 제목·담당자가
|
||||
간다 — 화면에선 비멤버 Admin 이 그 프로젝트를 못 보지만 메일로는 제목을 받는다(4장 관리자 보고 정책).
|
||||
|
||||
## 6-16. 용어 "업무" · 섹션 담당자 바로 지정 · 세부 업무 협업자 · 반응 알림 · 전체 보기 대시보드 (2026-10-13, 마이그레이션 없음)
|
||||
|
||||
- **용어 "작업" → "업무"** — Project 모듈의 화면 글자·메시지·서버 오류 문구·알림 제목(`업무 배정:`·`업무 완료:`·메일 제목)·도움말 전부
|
||||
(조사도 맞춤: 업무를·업무가·업무로). 코드 식별자·주석·DB 는 그대로. 이미 쌓인 알림 행 제목은 예전 글자 그대로라, 큰 알림 팝업은
|
||||
`나를 태그함|업무 배정|작업 배정` 접두어를 모두 뗀다. PC 알림 프로그램(`desktop/notifier`) 소스도 둘 다 떼도록 바꿨다 —
|
||||
**다시 빌드해 배포하기 전의 exe 는 새 알림에 "업무 배정:" 접두어가 제목에 남아 보인다**(기능 영향 없음).
|
||||
- **섹션 제목 오른쪽 담당자** — 보드 섹션 머리·목록 섹션 줄의 기본 담당자 아이콘(`stageAssigneeHtml`). 편집 권한자는 눌러서
|
||||
멤버 메뉴(`openStageAssigneeMenu` → `PUT /api/projects/{id}/stages/{sid}` `default_assignee_email`), 없으면 점선 원 아이콘. 접힌 보드 섹션에서는 숨김.
|
||||
- **접은 섹션 제목은 보통 굵기** — 보드 `.pj-col.is-collapsed .pj-col-name`, 목록 `.pj-list-group-head.is-collapsed .pj-list-group-name` 은
|
||||
`font-weight: 400`, 펼치면 다시 굵게(6-12).
|
||||
- **업무 창 세부 업무 줄 협업자** — 담당자 아이콘 오른쪽 `.pj-subtask-fol`(없으면 점선 원 두 사람, 줄 hover 때만 / 있으면 첫 사람 + "+N").
|
||||
누르면 멤버 메뉴(협업자는 ✓) → 그 세부 업무의 `POST/DELETE /api/tasks/{sub}/followers`. 데이터는 `GET /api/tasks/{id}` 의
|
||||
`subtasks[].followers`(`db.list_followers_of` 로 한 번에, 008 미적용·읽기 전용이면 없음 → 아이콘 숨김).
|
||||
- **댓글 반응 알림** — 6-7.
|
||||
- **전체 보기 → 대시보드** — 6-12.
|
||||
- **대시보드 업무 목록 패널 → 편집 창** — 패널 줄을 누르면 편집 창(`#pj-modal-task.pj-beside-drawer`)의 `right` 를 패널 폭(배율이면 `/ uiZoom()`)으로
|
||||
두어 패널 왼쪽에서 슬라이드로 열린다(`overflow:hidden` 이라 슬라이드 중 패널을 덮지 않음). 고른 줄은 `.is-current`. 편집 창 바깥(왼쪽) 클릭은
|
||||
예전처럼 편집 창 닫기 → 패널 다시 그림. 패널을 닫으면 편집 창은 화면 오른쪽 끝으로.
|
||||
- 검증: `tests/test_project_module.py::test_subtask_followers_and_reaction_alert`(실제 PG), `tests/js/project_ui.test.js`
|
||||
([섹션 담당자]·[세부 업무 협업자]·[대시보드 담당자별] 패널 왼쪽·[전체 보기] 기본 대시보드).
|
||||
|
||||
## 6-17. 세부 업무 만들 때 협업자 · 카드 세부 업무 협업자 · 대시보드 프로젝트별 · 마감 지난 업무 위쪽 알림 (2026-10-13, 마이그레이션 없음)
|
||||
|
||||
- **만들 때 협업자** — `POST /api/projects/{id}/tasks` 에 `followers: [이메일]`(선택). `_check_followers` 가 협업자 추가 API 와 같은 기준
|
||||
(`access.can_assign` — 그 프로젝트를 볼 수 있는 사람)으로 먼저 검사해 하나라도 안 되면 400(업무를 만들지 않음), 목록이 아니어도 400.
|
||||
만든 뒤 자동 협업자(만든 사람·담당자)와 함께 `_follow`. 화면:
|
||||
· 업무 창 세부 업무 추가 칸 — 담당자 오른쪽 **[협업자 없음 / 협업자 N명]** 버튼(`#pj-subtask-add-followers`), [추가] 뒤·다른 업무를 열면 비움.
|
||||
· 보드 카드 "+ 세부 업무 추가" 새 줄 — 담당자 오른쪽 협업자 아이콘(`.pj-card-subnew-fol`, 초안 `followers`). 협업자만 고른 줄은 바깥 클릭으로 닫히지 않는다.
|
||||
· 보드 "+ 메인 업무 추가" 입력 카드 — 담당자 옆 협업자 아이콘(`.pj-tasknew-fol`, 초안 `followers`, 담당자는 후보에서 빠지고 담당자로 고르면 협업자에서 빠짐).
|
||||
· 이미 있는 보드 카드(메인 업무) — 아래줄 담당자 오른쪽 협업자 아이콘(`.pj-card-fol`). 카드 목록엔 협업자 정보가 없어 비어 보이면 카드에 마우스를
|
||||
올릴 때만 보이고, 누르면 `GET /api/tasks/{id}/followers` 로 받아 멤버 메뉴(`openCardFollowers`). 받거나 고친 협업자는 `cardFollowers` 에 두어
|
||||
이 화면에서 카드에 계속 보이고, 업무 창을 닫으면 비운다(창에서 바꿨을 수 있다).
|
||||
- **이미 있는 세부 업무** — 업무 창 줄(`.pj-subtask-fol`, 6-16)은 비어 있어도 늘 옅게 보이게(예전엔 마우스를 올릴 때만), 보드 카드 펼친 세부 업무 줄에도
|
||||
협업자 아이콘(`.pj-card-sub-fol`, 편집 권한자, 비어 있으면 줄 hover 때만). 셋 다 공용 `openFollowerMenu`(멤버 메뉴, 협업자 ✓, 고를 때마다
|
||||
같은 자리에 다시 열려 여러 명) · `followerIconHtml` · `setTaskFollower`.
|
||||
- **대시보드 업무 합계(프로젝트별)** — 완료 상태별 카드 바로 왼쪽(`dashProjectBars`). 지금 범위의 메인 업무를 원 소속 프로젝트별로 묶어
|
||||
색 점·이름·가로 막대(채움 = 완료율)·완료/전체 · %, 업무 많은 순, 줄을 누르면 그 프로젝트(`/project/p/{id}`). 넘치면 카드 안 세로 스크롤.
|
||||
- **마감 지난 내 업무 알림** — `static/erp-overdue.js`·`erp-overdue.css`, ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html`) 위쪽 가운데
|
||||
(body 에 붙음, z 5500 — 긴급 공지 6000 아래). `GET /project/api/my-overdue` = 내가 담당인 미완료 업무(세부 포함) 중 마감일 < 오늘(KST),
|
||||
지금 볼 수 있는 것만(`access.filter_visible_tasks`), 마감 오래된 순 최대 200건(`db.list_my_overdue`). 알림은 최대 5줄 + "그 밖에 N건 — 내 업무에서 보기",
|
||||
줄 = `/project/t/{id}`(마감 M/D · N일 지남). **[닫기]**(버튼 글자 "닫기"만 — 2026-10-14 "(1시간 뒤 다시)" 글자·말풍선 뺌) = localStorage `erp_overdue_snooze`({until, ids}) — 이 브라우저 모든 탭이
|
||||
1시간 쉬고, 닫을 때 없던 업무가 새로 마감을 넘기면 바로 다시 띄운다. 5분마다·창을 다시 볼 때 확인, 다 완료하면 사라짐.
|
||||
401·403(Project 권한 없음)·404·503 이면 조용히 멈춤, iframe 안에서는 안 돈다. 새 환경변수·DB 변경 없음.
|
||||
- 검증: `tests/test_project_module.py::test_create_with_followers_and_my_overdue`(실제 PG), `tests/js/project_ui.test.js`
|
||||
([세부 추가 협업자]·[카드 세부 협업자]·[카드 새 세부 협업자]·[대시보드 프로젝트별]), `tests/js/overdue_ui.test.js`.
|
||||
|
||||
## 6-18. 업무를 다른 프로젝트로 이동 — 왼쪽 프로젝트 목록으로 드래그 (2026-10-13, 마이그레이션 없음)
|
||||
|
||||
- **화면**: 보드 카드를 끌어 왼쪽 사이드바의 프로젝트 줄에 놓는다(놓일 줄 강조 `.pj-tree-row.is-task-drop`). 카드 드래그는 섹션 이동용
|
||||
`text/plain` 에 더해 `application/x-pj-task`(= 업무 id, `TASK_DRAG_TYPE`)를 싣고, 사이드바(`initSideTree`)는 이 종류만 받아
|
||||
`pj:task-to-project` 이벤트를 낸다 → 프로젝트 화면이 **섹션 선택 창**(`openMoveToProject`, body 에 붙음 — 대상 프로젝트 섹션 목록,
|
||||
첫 진행 섹션이 기본, 섹션이 없으면 "섹션 없음") → [이동](Enter) = `POST /api/tasks/{id}/move-project` → `softSyncProjectRef` 로 다시 그림.
|
||||
같은 프로젝트·세부 업무는 창 없이 안내. 대상 프로젝트 멤버가 아니면 섹션 목록 조회가 403 → 안내.
|
||||
- **API** `POST /api/tasks/{id}/move-project` `{project_id, stage_id|null}` — 원 소속 권한(FULL) + 대상 프로젝트 관리 권한(멤버, 403).
|
||||
`db.move_task_to_project` 한 트랜잭션: 메인 업무만(세부 업무면 400, 같은 프로젝트 400, 남의 섹션 400), 세부 업무(모든 단계)도 project_id 변경,
|
||||
대상 섹션 목록 끝, 섹션 이동과 같은 규칙(담당자가 비면 섹션 기본 담당자 — 배정 알림, 완료 섹션이면 완료 — 완료 알림), 대상 프로젝트로의
|
||||
연결(`task_project_links`)은 지움(다른 연결은 유지), `project_activity`·`project_notifications`·`goal_meeting_tasks` 의 프로젝트도 따라 바꿈,
|
||||
활동 `project_moved`("업무: 옛 프로젝트 → 새 프로젝트"). 응답 `unseen` = 대상 프로젝트를 볼 수 없는 담당자·협업자(화면이 안내 — 담당자는 그대로 둔다).
|
||||
- 아직 안 되는 것: 목록·캘린더·타임라인 보기에서 끌기(보드 카드만), 이동 되돌리기(다시 끌어 옮기면 됨).
|
||||
- 검증: `tests/test_project_module.py::test_move_task_to_other_project`(실제 PG), `tests/js/project_ui.test.js` [프로젝트 이동].
|
||||
|
||||
## 6-19. 담당자는 협업자가 아니다 · 세부 업무 추가 칸 아이콘 · 내 업무 오른쪽 업무 창 · 섹션별 카드 삭제 (2026-10-13, 마이그레이션 028)
|
||||
|
||||
- **규칙 — 협업자는 담당자 외의 멤버**(업무·세부 업무 모두). 예전엔 담당자를 자동 협업자로 넣었다.
|
||||
· `db.add_followers` 가 그 업무의 담당자를 SQL 에서 거른다 — 자동 협업자(만든 사람·댓글 쓴 사람·@태그)·만들 때 고른 협업자 모두.
|
||||
· 담당자를 정하면(`db.update_task` — 직접 지정·섹션 기본 담당자, `move_task_to_project` 의 기본 담당자) 같은 트랜잭션에서 그 사람을
|
||||
협업자에서 뺀다(`_drop_assignee_follower`). 예전 담당자를 협업자로 자동으로 넣지는 않는다.
|
||||
· `POST /api/tasks/{id}/followers` 에 담당자(빈 email = 나 자신이 담당자인 경우 포함)는 400.
|
||||
· 화면: 협업자 고르기 메뉴(`openFollowerMenu` 의 assignee 인자)·업무 창 협업자 추가 메뉴에서 담당자를 뺀다, 내가 담당자면 [협업자로 참여] 숨김,
|
||||
담당자를 바꾸면 화면의 협업자 목록에서도 바로 뺀다. 알림은 그대로 — 수신자 = 담당자 + 협업자(`_task_recipients`).
|
||||
· **마이그레이션 028**(`project_db_028_followers_exclude_assignee.sql`) — 이미 겹친 `task_followers` 행(담당자와 같은 사람)을 지운다.
|
||||
스키마 변경 없음, 멱등(008 미적용이면 건너뜀), 지운 행 수를 NOTICE 로. 되돌리기 = 적용 전 백업에서 task_followers 복원.
|
||||
- **세부 업무 추가 칸**(업무 창) — 담당자·협업자·마감일은 글자 없는 동그라미 아이콘 버튼(담당자 = 아바타/점선 원, 협업자 = 첫 사람 + "+N"/점선 원
|
||||
두 사람, 마감일 = 점선 원 달력 → 고르면 아이콘 + 날짜), 말풍선에 담당자 이름·협업자 목록. 남는 폭은 제목 칸이 다 쓴다(`.pj-subtask-form` nowrap).
|
||||
- **내 업무 화면** — 줄(남의 상위 업무 안내 줄 포함)을 누르면 화면 이동 없이 오른쪽 업무 창(`createEmbedTaskPanel` — `/project/t/{id}?embed=1`
|
||||
iframe, 수신함·회의록과 같은 저장 대기). 다른 줄 = 같은 창에서 바꿈, Esc·목록 밖 클릭 = 닫기 → 목록 다시 받기. 연 줄은 `.is-panel-selected`.
|
||||
Ctrl·가운데 클릭 = 새 탭 프로젝트 화면, 우클릭 "프로젝트 화면에서 열기".
|
||||
- **대시보드** — "미완료 업무 합계(섹션별)" 카드 삭제(요청). 남은 카드: 업무 합계(프로젝트별)·업무 합계(완료 상태별)·담당자별(Pro user 이상).
|
||||
- 검증: `tests/test_project_module.py::test_assignee_is_never_follower`(실제 PG, 028 두 번 실행 포함),
|
||||
`tests/test_project_review_fixes.py`(같은 트랜잭션에서 협업자 정리), `tests/js/project_ui.test.js` [내 업무 창](`render_project.py` 가 `mytasks_render.html` 도 만든다).
|
||||
|
||||
## 6-20. 세부 업무 자동 협업자 없음 · 마감일 아이콘 옅게 · 담당자별 패널 날짜 (2026-10-14)
|
||||
|
||||
- **세부 업무를 만들 때 만든 사람을 자동 협업자로 넣지 않는다** — 만들 때 고른 협업자만(`_create_task_for`: `parent_task_id`
|
||||
가 있으면 `_follow` 에 만든 사람을 빼고 고른 사람만). 담당자도 자동 지정되지 않는다(세부 업무는 섹션이 없어 기본 담당자 없음).
|
||||
메인 업무는 그대로 만든 사람 자동 협업자. 화면 `newTaskFollowers` 도 같은 규칙(고른 사람만). 이미 만든 세부 업무의 협업자는 그대로.
|
||||
- **업무 창 세부 업무 줄 마감일 아이콘** — 마감일이 없을 때 점선 원 달력 아이콘을 협업자 아이콘처럼 늘 옅게(`opacity .5`, 줄 hover = 진하게).
|
||||
- **대시보드 담당자별 합계 → 오른쪽 업무 목록 패널** — 오른쪽 날짜 `mm/dd(요일)`(예: 10/07(수)), 마감이 지난 미완료 업무는 빨간 굵은 글씨(`em.is-overdue`).
|
||||
- **로그인 전 화면 주소 → 로그인 화면**: 공유한 회의록·업무 주소를 로그인 안 된(세션 만료·다른 브라우저) 상태로 열면
|
||||
예전엔 `{"detail":"로그인이 필요합니다."}` JSON 이 보였다. 화면 주소(내 업무·프로젝트·휴지통·도움말·수신함·목표·회의록)는
|
||||
`_page_user` 가 `/login?next=<원래 주소>` 로 보내 로그인 뒤 그 주소로 돌아온다(`/t/{id}`·`/notifier` 는 원래 그렇게 동작). API 는 그대로 401.
|
||||
- 검증: `test_create_with_followers_and_my_overdue`(세부 = 고른 사람만, 메인 = 만든 사람), `project_ui.test.js` [대시보드 담당자별] 패널 날짜,
|
||||
`tests/test_project_meeting_nav.py::PageLoginRedirectTests`.
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
| 쿠팡 밀크런 | 쿠팡 출고 일정 관리 (`app/modules/cupang/`) — 월간 달력 / 출고 묶음(헤더+라인) / 상자 입수량 자동계산 / 로켓 매출 관리 / 엑셀 내보내기. 상품은 `itemcode_db` 읽기 전용 참조 |
|
||||
| 휴가 (준비중) | 연차/반차/특별휴가 신청·잔여일수 관리 |
|
||||
| 말레이시아 재고 | 말레이시아 창고 재고관리 (`app/modules/malaysia/`) — 낱개 입출고/조정, 세트 BOM, 일일 재고조사(세트 분해 자동 반영), 현재고 현황. 상품명은 `itemcode_db` 읽기 전용 참조 |
|
||||
| 긴급 공지 | 수퍼관리자가 정한 시각에 전체/고른 사람의 ERP 화면 정가운데에 띄우는 공지(`app/modules/notice/`, project_db 024) — [확인] 전까지 다시 뜸, 확인 현황. `docs/NOTICE_MODULE.md` |
|
||||
| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
|
||||
|
||||
### 권한 키 (`MODULE_KEYS`)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 002 — 쇼핑몰별 수동 입력 + 열 순서
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 기존 데이터 삭제 없음. 운영: /opt/www/main 에서 기존 performance_db 에 superuser 로 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_002_manual_sales.sql
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청):
|
||||
-- 1) 설정 → 쇼핑몰마다 "수동 입력" 사용 여부(perf_marketplaces.manual_input). 켜면 실적 일자별 표의 그 쇼핑몰
|
||||
-- 날짜 칸에 매출(총매출)을 직접 넣는다 — 넣은 날은 그 값이 API 수집값을 대신한다(비우면 다시 API 값).
|
||||
-- 끄면 넣어 둔 값은 남지만 집계에 쓰지 않는다.
|
||||
-- 2) 열 순서: 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON (sort_order 만 바꿈).
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
COMMENT ON COLUMN perf_marketplaces.manual_input IS '수동 입력 사용 — 켜면 perf_manual_sales 값이 그날 API 수집값을 대신한다';
|
||||
|
||||
-- 수동 입력 매출 — 쇼핑몰 × 날짜 하나에 값 하나(원 단위 정수, 총매출). 수수료는 다른 매출처럼 요율로 계산.
|
||||
CREATE TABLE IF NOT EXISTS perf_manual_sales (
|
||||
marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
|
||||
sales_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (marketplace_code, sales_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales;
|
||||
CREATE TRIGGER trg_perf_manual_sales_updated
|
||||
BEFORE UPDATE ON perf_manual_sales
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_manual_sales TO performance_app;
|
||||
|
||||
-- 열 순서(설정·실적 표 공통)
|
||||
UPDATE perf_marketplaces AS m SET sort_order = v.sort_order
|
||||
FROM (VALUES ('cafe24', 10), ('naver', 20), ('coupang', 30), ('toss', 40), ('gsshop', 50), ('elevenst', 60),
|
||||
('ohouse', 70), ('gmarket', 80), ('kakao', 90), ('lotteon', 100)) AS v(code, sort_order)
|
||||
WHERE m.code = v.code AND m.sort_order <> v.sort_order;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 002 manual sales ready' AS status;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 003 — 쇼핑몰 열 순서 + 쿠팡(윙) 이름 + 수동 입력 전용 쇼핑몰 2곳
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 기존 데이터 삭제 없음. 002(manual_input) 적용 뒤에 실행.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_003_marketplace_order.sql
|
||||
--
|
||||
-- 왜(2026-10-13 사용자 요청):
|
||||
-- 1) 기존 '쿠팡'(WING API — 판매자배송 + 로켓그로스) 이름을 '쿠팡(윙)' 으로.
|
||||
-- 2) 신규 쇼핑몰 '쿠팡(로켓)'(coupang_rocket)·'애터미아자몰'(atomy) — API 연동 없는 수동 입력 전용(manual_input = TRUE).
|
||||
-- 3) 열 순서: 카페24 · 네이버 · 쿠팡(윙) · 쿠팡(로켓) · 오늘의집 · G마켓 · 카카오 · GS샵 · 11번가 · 롯데ON · 토스 · 애터미아자몰.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
UPDATE perf_marketplaces SET name = '쿠팡(윙)' WHERE code = 'coupang' AND name = '쿠팡';
|
||||
|
||||
INSERT INTO perf_marketplaces (code, name, sort_order, manual_input) VALUES
|
||||
('coupang_rocket', '쿠팡(로켓)', 35, TRUE),
|
||||
('atomy', '애터미아자몰', 110, TRUE)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
-- 수동 입력 전용은 늘 켜 둔다(화면에서도 끌 수 없음)
|
||||
UPDATE perf_marketplaces SET manual_input = TRUE
|
||||
WHERE code IN ('coupang_rocket', 'atomy') AND NOT manual_input;
|
||||
|
||||
-- 열 순서(설정·실적 표 공통)
|
||||
UPDATE perf_marketplaces AS m SET sort_order = v.sort_order
|
||||
FROM (VALUES ('cafe24', 10), ('naver', 20), ('coupang', 30), ('coupang_rocket', 35), ('ohouse', 40),
|
||||
('gmarket', 50), ('kakao', 60), ('gsshop', 70), ('elevenst', 80), ('lotteon', 90),
|
||||
('toss', 100), ('atomy', 110)) AS v(code, sort_order)
|
||||
WHERE m.code = v.code AND m.sort_order <> v.sort_order;
|
||||
|
||||
COMMIT;
|
||||
SELECT code, name, sort_order, manual_input FROM perf_marketplaces ORDER BY sort_order;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 004 — 쇼핑몰 이름 '네이버 스마트스토어' → '네이버'
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 이름만 바꾼다(매출·인증정보 그대로).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_004_naver_name.sql
|
||||
-- 왜(2026-10-13 사용자 요청): 설정·실적 화면의 쇼핑몰 이름을 '네이버' 로 통일.
|
||||
-- =====================================================================
|
||||
UPDATE perf_marketplaces SET name = '네이버' WHERE code = 'naver' AND name = '네이버 스마트스토어';
|
||||
SELECT code, name, sort_order FROM perf_marketplaces WHERE code = 'naver';
|
||||
@@ -0,0 +1,36 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 005 — 광고비(채널 × 날짜)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 새 표 하나만 만든다(기존 표·데이터 그대로). 운영: /opt/www/main 에서 superuser 로 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_005_ad_spend.sql
|
||||
--
|
||||
-- 왜(2026-10-13 사용자 요청): 실적 모듈 "광고비" 탭 — 구글·메타·쿠팡(윙)·쿠팡(로켓) 광고비를 연·월·일로.
|
||||
-- 쿠팡(로켓)은 광고 보고서 파일 업로드(1열 날짜, 19열 청구금액(+부가가치세)), 나머지는 날짜 칸 직접 입력.
|
||||
-- 채널 목록은 앱(app/modules/performance/ad_spend.py CHANNELS)이 정한다 — 채널을 늘려도 이 표는 그대로.
|
||||
-- 되돌리기: DROP TABLE perf_ad_spend; (광고비 데이터만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS perf_ad_spend (
|
||||
channel_code TEXT NOT NULL,
|
||||
spend_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
source TEXT NOT NULL DEFAULT 'manual' CHECK (source IN ('manual', 'upload', 'api')),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (channel_code, spend_date)
|
||||
);
|
||||
COMMENT ON TABLE perf_ad_spend IS '광고비 — 채널(google·meta·coupang_wing·coupang_rocket) × 날짜 하나에 금액 하나(원)';
|
||||
COMMENT ON COLUMN perf_ad_spend.source IS 'manual=화면 직접 입력, upload=파일 업로드, api=광고 API 수집';
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_ad_spend_date ON perf_ad_spend (spend_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_ad_spend_updated ON perf_ad_spend;
|
||||
CREATE TRIGGER trg_perf_ad_spend_updated
|
||||
BEFORE UPDATE ON perf_ad_spend
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_spend TO performance_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 005 ad spend ready' AS status;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 006 — 광고비 ROAS·보고서 상세 항목
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). perf_ad_spend 에 열 두 개만 추가(기존 행·값 그대로). 005 다음에 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_006_ad_roas_metrics.sql
|
||||
--
|
||||
-- 왜(2026-10-14 사용자 요청): 네이버 광고 보고서 업로드 — 12열 구매완료 광고수익률(%)을 그날 ROAS 로(roas),
|
||||
-- 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로(metrics)
|
||||
-- 보관해 네이버 머리글을 누르면 일자별 표로 본다. 구글·메타도 나중에 같은 칸에 ROAS 를 넣는다.
|
||||
-- 되돌리기: ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas; (보고서 ROAS·상세만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS roas NUMERIC(14, 2);
|
||||
ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS metrics JSONB;
|
||||
COMMENT ON COLUMN perf_ad_spend.roas IS '광고 보고서의 ROAS(%) — 구글·메타·네이버(계산하지 않고 보고서 값). NULL = 없음';
|
||||
COMMENT ON COLUMN perf_ad_spend.metrics IS '광고 보고서 그날 나머지 항목 {머리글: 값} — 네이버 노출수·클릭수·전환수 등';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 006 ad roas/metrics ready' AS status;
|
||||
@@ -62,25 +62,29 @@ CREATE TABLE IF NOT EXISTS perf_marketplaces (
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
include_in_sales BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
manual_input BOOLEAN NOT NULL DEFAULT FALSE, -- 수동 입력 사용(002) — perf_manual_sales 값이 그날 API 값을 대신
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
DROP TRIGGER IF EXISTS trg_perf_marketplaces_updated ON perf_marketplaces;
|
||||
CREATE TRIGGER trg_perf_marketplaces_updated
|
||||
BEFORE UPDATE ON perf_marketplaces
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
INSERT INTO perf_marketplaces (code, name, sort_order) VALUES
|
||||
('cafe24', '카페24', 10),
|
||||
('naver', '네이버 스마트스토어', 20),
|
||||
('coupang', '쿠팡', 30),
|
||||
('ohouse', '오늘의집', 40),
|
||||
('gmarket', 'G마켓', 50),
|
||||
('kakao', '카카오', 60),
|
||||
('gsshop', 'GS샵', 70),
|
||||
('elevenst', '11번가', 80),
|
||||
('lotteon', '롯데ON', 90),
|
||||
('toss', '토스쇼핑', 100)
|
||||
INSERT INTO perf_marketplaces (code, name, sort_order, manual_input) VALUES
|
||||
('cafe24', '카페24', 10, FALSE),
|
||||
('naver', '네이버', 20, FALSE),
|
||||
('coupang', '쿠팡(윙)', 30, FALSE),
|
||||
('coupang_rocket', '쿠팡(로켓)', 35, TRUE), -- 수동 입력 전용(003)
|
||||
('ohouse', '오늘의집', 40, FALSE),
|
||||
('gmarket', 'G마켓', 50, FALSE),
|
||||
('kakao', '카카오', 60, FALSE),
|
||||
('gsshop', 'GS샵', 70, FALSE),
|
||||
('elevenst', '11번가', 80, FALSE),
|
||||
('lotteon', '롯데ON', 90, FALSE),
|
||||
('toss', '토스쇼핑', 100, FALSE),
|
||||
('atomy', '애터미아자몰', 110, TRUE) -- 수동 입력 전용(003)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
@@ -208,13 +212,31 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_perf_sync_running
|
||||
ON perf_sync_runs (marketplace_code) WHERE status = 'running';
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_sync_runs_code ON perf_sync_runs (marketplace_code, started_at DESC);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 7) 수동 입력 매출(002) — 쇼핑몰 × 날짜 하나에 총매출 하나. 그 쇼핑몰 수동 입력이 켜져 있을 때만 집계에 쓴다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS perf_manual_sales (
|
||||
marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
|
||||
sales_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (marketplace_code, sales_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales;
|
||||
CREATE TRIGGER trg_perf_manual_sales_updated
|
||||
BEFORE UPDATE ON perf_manual_sales
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 권한 — 앱 계정은 DML 만
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO performance_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON
|
||||
perf_marketplaces, perf_commission_rates, perf_credentials,
|
||||
perf_connection_status, perf_sales_events, perf_sync_runs
|
||||
perf_connection_status, perf_sales_events, perf_sync_runs, perf_manual_sales
|
||||
TO performance_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO performance_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 024 — 긴급 공지(ERP 전체 화면 가운데 공지)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청): 수퍼관리자가 제목·내용(이미지 포함) 공지를 만들어, 정한 시각에, 전체 또는 고른
|
||||
-- 사람에게 ERP 어느 화면에서든 화면 가로·세로 가운데에 띄운다. 받는 사람이 [확인]을 누를 때까지 화면을 열 때마다
|
||||
-- 다시 뜨고, 누가 확인했는지 남는다. 공지 이미지는 DB(bytea)에 둔다 — 백업에 함께 들어가고 디스크 파일 정리가 없다.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS urgent_notices (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
body_html TEXT NOT NULL DEFAULT '', -- 서버가 정리한 HTML(이미지는 /notice/images/{id} 만)
|
||||
show_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 이 시각부터 띄운다
|
||||
to_all BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE 면 urgent_notice_targets 의 사람만
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
cancelled_at TIMESTAMPTZ NULL, -- 취소(더 띄우지 않음) — 기록은 남긴다
|
||||
cancelled_by TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_urgent_notices_show ON urgent_notices (show_at) WHERE cancelled_at IS NULL;
|
||||
COMMENT ON TABLE urgent_notices IS '긴급 공지 — 수퍼관리자 작성, show_at 부터 받는 사람 화면 가운데, [확인] 전까지';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS urgent_notice_targets (
|
||||
notice_id BIGINT NOT NULL REFERENCES urgent_notices(id) ON DELETE CASCADE,
|
||||
user_email TEXT NOT NULL,
|
||||
PRIMARY KEY (notice_id, user_email)
|
||||
);
|
||||
COMMENT ON TABLE urgent_notice_targets IS '긴급 공지 받는 사람(to_all = FALSE 일 때)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS urgent_notice_acks (
|
||||
notice_id BIGINT NOT NULL REFERENCES urgent_notices(id) ON DELETE CASCADE,
|
||||
user_email TEXT NOT NULL,
|
||||
acked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (notice_id, user_email)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_urgent_notice_acks_user ON urgent_notice_acks (user_email);
|
||||
COMMENT ON TABLE urgent_notice_acks IS '긴급 공지 [확인] 기록 — 한 사람 한 번';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS urgent_notice_images (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
notice_id BIGINT NULL REFERENCES urgent_notices(id) ON DELETE CASCADE, -- 저장 전 올린 이미지는 NULL
|
||||
filename TEXT NOT NULL DEFAULT '',
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
data BYTEA NOT NULL,
|
||||
uploaded_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_urgent_notice_images_notice ON urgent_notice_images (notice_id);
|
||||
COMMENT ON TABLE urgent_notice_images IS '긴급 공지 본문 이미지(png·jpeg·gif·webp, 10MB 이하)';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON urgent_notices, urgent_notice_targets, urgent_notice_acks, urgent_notice_images TO project_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 024 urgent notices ready' AS status;
|
||||
@@ -0,0 +1,37 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 025 — 주간 회의록 "작업 등록" 표를 서버에(주차별, 모두가 같은 표)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청): 작업 등록 표가 각자 브라우저(localStorage)에만 저장돼 다른 사람이 적거나 등록한 줄이
|
||||
-- 보이지 않았다. 주차(회의록 주차 시작일)마다 한 표를 서버에 두고 모두가 같이 본다. 줄은 [적용] 전까지 고칠 수 있고,
|
||||
-- [적용] = 그 프로젝트에 작업을 만들고 task_id 를 남긴다(두 번 눌러도 한 번만 — 서버가 줄을 잠그고 확인).
|
||||
-- parent_id = 세부 작업 줄(위 줄의 작업 밑에 세부 작업으로 만든다 — 화면은 다음 단계).
|
||||
-- 회의록 행(goal_meetings)과 묶지 않는다 — 회의록을 만들기 전에도 그 주차 표를 쓸 수 있고, 회의록을 지워도 남는다.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_meeting_tasks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
week_start DATE NOT NULL, -- 회의록 주차 시작일(store.month_weeks)
|
||||
parent_id BIGINT NULL REFERENCES goal_meeting_tasks(id) ON DELETE CASCADE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '' CHECK (char_length(title) <= 200),
|
||||
assignee_email TEXT NOT NULL DEFAULT '',
|
||||
project_id BIGINT NULL REFERENCES projects(id) ON DELETE SET NULL,
|
||||
stage_id BIGINT NULL REFERENCES project_stages(id) ON DELETE SET NULL,
|
||||
task_id BIGINT NULL, -- [적용]으로 만든 작업(작업을 지워도 기록은 남는다 — FK 없음)
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_meeting_tasks_week ON goal_meeting_tasks (week_start, sort_order, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_meeting_tasks_parent ON goal_meeting_tasks (parent_id);
|
||||
COMMENT ON TABLE goal_meeting_tasks IS '주간 회의록 작업 등록 표 — 주차별, [적용] 전 줄 + 만든 작업(task_id)';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_meeting_tasks TO project_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 025 meeting quick tasks ready' AS status;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 026 — 회의록 작업 등록 표: "작업" 칸(이미 있는 작업의 세부 작업으로 등록)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열 하나만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청): 작업 등록 표에서 프로젝트 → 섹션 → **작업** 까지 고를 수 있게 — 작업을 고르면 [적용] 때
|
||||
-- 그 작업의 세부 작업으로 만든다(비우면 예전처럼 그 섹션에 새 작업). 025 의 parent_id(표 안 줄끼리의 세부 작업)는
|
||||
-- 화면에서 쓰지 않는다(열·값은 그대로 둔다).
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_meeting_tasks ADD COLUMN IF NOT EXISTS parent_task_id BIGINT NULL; -- 고른 상위 작업(tasks.id, FK 없음 — 작업이 지워져도 줄은 남는다)
|
||||
COMMENT ON COLUMN goal_meeting_tasks.parent_task_id IS '작업 칸 — [적용] 때 이 작업의 세부 작업으로 만든다(NULL = 그 섹션에 새 작업)';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 026 meeting quick parent task ready' AS status;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 027 — 주간 회의록: 같은 항목 칸 안에 줄 추가(항목 칸 묶음)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열 하나만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청): 회의록 표 "주요 업무" 칸에서 위/아래 줄 추가를 하면 "항목" 칸은 그대로 두고
|
||||
-- 그 항목 안에 줄이 늘어나게(연간 목표 goal_rows.label_cont(016)와 같은 방식).
|
||||
-- label_cont = true 인 줄은 바로 위 줄(같은 구역)의 항목 칸에 이어 붙는다 — 항목 이름은 묶음 첫 줄에만.
|
||||
-- 줄마다 주요 업무·정량 목표·지난주 결과·연결키(line_key)는 따로다. 다음 주차 회의록은 묶음을 그대로 이어받는다.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS label_cont BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
COMMENT ON COLUMN goal_meeting_items.label_cont IS '바로 위 줄(같은 구역)의 항목 칸에 이어 붙는 줄 — 항목 이름은 묶음 첫 줄에';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 027 meeting label groups ready' AS status;
|
||||
@@ -0,0 +1,31 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 028 — 담당자는 협업자에서 제외(데이터 정리)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 스키마 변경 없음 — 업무(세부 업무 포함)의 담당자와 같은 사람인 협업자 행만 지운다.
|
||||
-- 운영: /opt/www/main 에서 기존 project_db 에 적용(적용 전 pg_dump 백업).
|
||||
--
|
||||
-- 왜(2026-10-13 사용자 요청): "모든 업무·세부 업무에서 담당자는 협업자에서 제외 — 협업자는 담당자 외의 멤버".
|
||||
-- 예전엔 담당자를 자동으로 협업자에 넣었다. 앱은 이제 담당자를 협업자로 넣지 않고(db.add_followers),
|
||||
-- 담당자가 바뀌면 그 사람을 협업자에서 뺀다(db.update_task). 이미 겹쳐 있는 행은 여기서 한 번 정리한다.
|
||||
-- 알림은 그대로 간다 — 업무 알림 수신자 = 담당자 + 협업자(라우터 _task_recipients).
|
||||
-- 되돌리기: 이 파일 적용 직전 백업에서 task_followers 만 복원(다른 표는 건드리지 않는다).
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
DO $$
|
||||
DECLARE n integer;
|
||||
BEGIN
|
||||
IF to_regclass('public.task_followers') IS NULL THEN
|
||||
RAISE NOTICE '028: task_followers 없음(008 미적용) — 건너뜀';
|
||||
RETURN;
|
||||
END IF;
|
||||
DELETE FROM task_followers f
|
||||
USING tasks t
|
||||
WHERE f.task_id = t.id
|
||||
AND COALESCE(t.assignee_email, '') <> ''
|
||||
AND lower(f.user_email) = lower(t.assignee_email);
|
||||
GET DIAGNOSTICS n = ROW_COUNT;
|
||||
RAISE NOTICE '028: 담당자와 겹친 협업자 % 행 삭제', n;
|
||||
END $$;
|
||||
|
||||
COMMIT;
|
||||
@@ -14,6 +14,14 @@ node tests/js/box_calc_ui.test.js
|
||||
|
||||
성공하면 마지막 줄에 `ALL PASS`, 실패하면 실패한 항목명이 출력되고 종료코드 1.
|
||||
|
||||
# 마감 지난 내 업무 알림 테스트 (jsdom)
|
||||
|
||||
`static/erp-overdue.js` — 위쪽 알림·최대 5줄·닫으면 1시간 쉼·새로 지난 업무는 바로·다 완료하면 사라짐·권한 없으면(403) 멈춤.
|
||||
|
||||
```bash
|
||||
node tests/js/overdue_ui.test.js # jsdom 필요(npm install jsdom 또는 NODE_PATH)
|
||||
```
|
||||
|
||||
# 연간 목표·주간 회의록 UI 테스트 (jsdom)
|
||||
|
||||
`goals.html`·`goal_meeting.html` + `static/project.js` — 칸 저장 직렬화·늦은 응답·503·초안 보호·구조 변경 중단·이번주 실적 %·
|
||||
|
||||
@@ -15,7 +15,8 @@ const ROOT = path.join(__dirname, "..", "..");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
const PAGE = {};
|
||||
["goals_admin", "goals_ro", "goals_weekly_admin", "meeting_admin", "meeting_err", "meeting_ro", "meeting_member"].forEach(function (n) {
|
||||
["goals_admin", "goals_ro", "goals_weekly_admin", "meeting_admin", "meeting_err", "meeting_ro", "meeting_member",
|
||||
"meeting_groups", "meeting_groups_added"].forEach(function (n) {
|
||||
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
|
||||
});
|
||||
const GOALS_URL = "http://localhost/project/goals/2026";
|
||||
@@ -352,6 +353,33 @@ function meetServer(env, st) {
|
||||
{ nav: env.navigations });
|
||||
});
|
||||
|
||||
// 첫 열(구분) — 구역 통째로 위/아래(우클릭·⋯), 맨 위는 "위로" 없음, 구역 첫 줄 id 로 요청
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
const blocks = Array.from(env.d.querySelectorAll("tbody.pj-meet-sec"));
|
||||
blocks[0].querySelector("th.pj-meet-c-sec").dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
let labels = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[1e] 첫 구역 우클릭 — 구역 아래로·구역 끝에 줄 추가(위로 없음)",
|
||||
labels.indexOf("구역 아래로") >= 0 && labels.indexOf("구역 위로") < 0 && labels.indexOf("구역 끝에 줄 추가") >= 0, labels);
|
||||
const gets0 = st.gets || 0; // 부팅 때 실적 자동 갱신이 이미 한 번 받는다
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "구역 아래로"; }).click();
|
||||
await settle(); await wait(20); await settle();
|
||||
const firstId = blocks[0].querySelector("tr[data-item]").dataset.item;
|
||||
const call = env.calls.find(function (c) { return /\/move-section$/.test(c.url); });
|
||||
// 2026-10-12 — 새로고침 대신 표만 서버에서 다시 받아 그 자리에서 바꿔 끼운다(연간 목표와 같은 애니메이션)
|
||||
check("[1e] 구역 아래로 → 그 구역 첫 줄로 move-section(direction 1) 후 표만 다시 받음(새로고침 없음)",
|
||||
!!call && call.method === "POST" && call.url.indexOf("/meeting-items/" + firstId + "/move-section") >= 0 &&
|
||||
call.body.direction === 1 && env.navigations === 0 && st.gets === gets0 + 1 &&
|
||||
!blocks[0].isConnected && env.d.querySelectorAll("tbody.pj-meet-sec").length === blocks.length, [call, env.navigations, st.gets]);
|
||||
const fresh = Array.from(env.d.querySelectorAll("tbody.pj-meet-sec"));
|
||||
const last = fresh[fresh.length - 1];
|
||||
last.querySelector('[data-meet-act="sec-menu"]').click();
|
||||
labels = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[1e] 마지막 구역 ⋯ — 구역 위로(아래로 없음)", labels.indexOf("구역 위로") >= 0 && labels.indexOf("구역 아래로") < 0, labels);
|
||||
});
|
||||
|
||||
// ════════════════════ [2] 숫자 — 늦은 응답이 최신 입력을 덮지 않음 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
@@ -492,23 +520,67 @@ function meetServer(env, st) {
|
||||
check("[2f] 창을 슬라이드 주소로", popup.location.href === "https://docs.google.com/presentation/d/abc/edit" && popup.focused);
|
||||
});
|
||||
|
||||
// ════════════════════ [2g] 머리 영역 3칸 — 결정 사항은 ②, 작업 등록 표(③): 칸 → 목록 → [적용] = 그 프로젝트에 작업 ════════════════════
|
||||
// 작업 등록 표 가짜 서버(025) — 주차별 줄, POST·PUT·DELETE·[적용]
|
||||
function quickServer(env, opts) {
|
||||
opts = opts || {};
|
||||
const st = { rows: {}, seq: 100, applied: [], deleted: [] };
|
||||
(opts.rows || []).forEach(function (r) { st.rows[r.id] = Object.assign({ week: "2026-09-28", task_id: null, visible: true }, r); });
|
||||
const out = function (r) {
|
||||
return { id: r.id, title: r.title || "", assignee_email: r.assignee_email || "", project_id: r.project_id || null,
|
||||
project_name: r.project_name || "", stage_id: r.stage_id || null, stage_name: r.stage_name || "", task_id: r.task_id,
|
||||
parent_task_id: r.parent_task_id || null, parent_task_title: r.parent_task_id ? (r.parent_task_title || "상세페이지 리뉴얼") : "",
|
||||
registered: r.task_id != null, visible: r.visible !== false, task_exists: true };
|
||||
};
|
||||
env.route("GET", /\/goals\/meetings\/([\d-]+)\/quick-tasks$/, function (u) {
|
||||
const w = /meetings\/([\d-]+)\//.exec(u)[1];
|
||||
return { body: { tasks: Object.values(st.rows).filter(function (r) { return r.week === w; }).map(out) } };
|
||||
});
|
||||
env.route("POST", /\/goals\/meetings\/([\d-]+)\/quick-tasks$/, function (u, b) {
|
||||
const r = Object.assign({ id: ++st.seq, week: /meetings\/([\d-]+)\//.exec(u)[1] }, b);
|
||||
st.rows[r.id] = r;
|
||||
return { status: 201, body: { task: out(r) } };
|
||||
});
|
||||
env.route("PUT", /\/meeting-quick-tasks\/(\d+)$/, function (u, b) {
|
||||
const r = st.rows[+/(\d+)$/.exec(u)[1]];
|
||||
Object.assign(r, b);
|
||||
return { body: { task: out(r) } };
|
||||
});
|
||||
env.route("DELETE", /\/meeting-quick-tasks\/(\d+)$/, function (u) {
|
||||
const id = +/(\d+)$/.exec(u)[1];
|
||||
st.deleted.push(id); delete st.rows[id];
|
||||
return { body: { ok: true } };
|
||||
});
|
||||
env.route("POST", /\/meeting-quick-tasks\/(\d+)\/apply$/, function (u) {
|
||||
const r = st.rows[+/(\d+)\/apply$/.exec(u)[1]];
|
||||
st.applied.push(Object.assign({}, r));
|
||||
if (r.task_id == null) { r.task_id = 555; return { status: 201, body: { task: out(r), created: true } }; }
|
||||
return { body: { task: out(r), created: false } };
|
||||
});
|
||||
return st;
|
||||
}
|
||||
|
||||
// ════════════════════ [2g] 머리 영역 3칸 — 결정 사항은 ②, 작업 등록 표(③): 칸 → 목록 → [적용] = 서버가 그 프로젝트에 작업 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
let posted = null;
|
||||
const q = quickServer(env);
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [
|
||||
{ id: 7, name: "브랜드", parent_id: null, owner_email: "owner@test.local" }, { id: 8, name: "하위", parent_id: 7 }] } }; });
|
||||
{ id: 7, name: "브랜드", parent_id: null, owner_email: "owner@test.local" }, { id: 8, name: "하위", parent_id: 7 },
|
||||
{ id: 9, name: "끝난 프로젝트", parent_id: null, status: "completed" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/7\/members$/, function () { return { body: { members: [{ user_email: "kim@test.local" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/7\/stages$/, function () { return { body: { stages: [{ id: 72, name: "진행", sort_order: 2 }, { id: 71, name: "할 일", sort_order: 1 }] } }; });
|
||||
env.route("POST", /\/project\/api\/projects\/7\/tasks$/, function (u, body) { posted = body; return { status: 201, body: { ok: true, task: { id: 555 } } }; });
|
||||
await boot(env);
|
||||
env.route("GET", /\/project\/api\/projects\/7\/stages$/, function () { return { body: { stages: [{ id: 72, name: "진행", sort_order: 2 }, { id: 71, name: "할 일", sort_order: 1 },
|
||||
{ id: 73, name: "완료", sort_order: 0, is_done_stage: true }] } }; });
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d, board = d.querySelector(".pj-meet-board");
|
||||
check("[2g] 머리 영역: 월 계획 · 결정 사항 · 작업 등록", !!board && board.children.length === 3 &&
|
||||
!!board.querySelector(".pj-meet-notes #pj-meet-notes") && !!board.querySelector("#pj-meet-quick"));
|
||||
const tr = d.querySelector("#pj-meet-quick tbody tr");
|
||||
const title = tr.querySelector("input[data-field=title]");
|
||||
check("[2g] 서버 표를 읽어 빈 줄 3개", env.calls.some(function (c) { return /\/meetings\/2026-09-28\/quick-tasks$/.test(c.url) && c.method === "GET"; }) &&
|
||||
d.querySelectorAll("#pj-meet-quick tbody tr").length === 3);
|
||||
const title = d.querySelector("#pj-meet-quick tbody tr input[data-field=title]");
|
||||
title.value = "상세페이지 수정"; title.dispatchEvent(new env.w.Event("input", { bubbles: true }));
|
||||
title.dispatchEvent(new env.w.Event("focusout", { bubbles: true }));
|
||||
await settle(); await wait(5); await settle();
|
||||
check("[2g] 제목을 쓰면 서버에 줄이 생김(POST)", Object.values(q.rows).length === 1 && Object.values(q.rows)[0].title === "상세페이지 수정", q.rows);
|
||||
const pickItem = async function (kind, label) {
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-pick="' + kind + '"]').click(); await settle(); await wait(5); await settle();
|
||||
const items = Array.from(d.querySelectorAll(".pj-ctxmenu-item"));
|
||||
@@ -518,29 +590,171 @@ function meetServer(env, st) {
|
||||
return items.map(itemLabel);
|
||||
};
|
||||
const projLabels = await pickItem("project", "브랜드");
|
||||
check("[2g] 프로젝트 목록 = 최상위 프로젝트", JSON.stringify(projLabels) === JSON.stringify(["브랜드"]), projLabels);
|
||||
check("[2g] 프로젝트 목록 = 맨 위 '새 프로젝트'(Pro user) + 최상위 프로젝트(완료 제외)", JSON.stringify(projLabels) === JSON.stringify(["새 프로젝트", "브랜드"]), projLabels);
|
||||
const row = d.querySelector("#pj-meet-quick tbody tr");
|
||||
check("[2g] 프로젝트 고르면 첫 섹션 자동", row.querySelector('[data-pick="stage"]').textContent === "할 일", row.querySelector('[data-pick="stage"]').textContent);
|
||||
check("[2g] 프로젝트 고르면 첫 섹션 자동(완료 섹션은 건너뜀)", row.querySelector('[data-pick="stage"]').textContent === "할 일", row.querySelector('[data-pick="stage"]').textContent);
|
||||
const stageLabels = await pickItem("stage", "할 일");
|
||||
check("[2g] 섹션 목록에 완료 섹션 없음", stageLabels.indexOf("완료") < 0 && stageLabels.indexOf("할 일") >= 0 && stageLabels.indexOf("진행") >= 0, stageLabels);
|
||||
const people = await pickItem("assignee", "Kim");
|
||||
check("[2g] 담당자 목록 = 그 프로젝트 소유자·멤버", people.indexOf("Owner") >= 0 && people.indexOf("Kim") >= 0, people);
|
||||
const saved = Object.values(q.rows)[0];
|
||||
check("[2g] 고른 칸은 서버 줄에 저장(PUT)", saved.project_id === 7 && saved.stage_id === 71 && saved.assignee_email === "kim@test.local", saved);
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="apply"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g] 적용 → 그 프로젝트에 작업 생성", posted && posted.title === "상세페이지 수정" && posted.stage_id === 71 && posted.assignee_email === "kim@test.local", posted);
|
||||
check("[2g] 등록된 줄은 '등록됨' 링크", /등록됨/.test(d.querySelector("#pj-meet-quick tbody tr").textContent) &&
|
||||
d.querySelector("#pj-meet-quick tbody tr a").getAttribute("href") === "/project/p/7?task=555");
|
||||
// 등록된 줄 삭제 → 확인 → 그 프로젝트의 작업도 삭제(DELETE), 줄 사라짐
|
||||
check("[2g] 적용 → 서버 [적용](그 줄로 작업 만들기)", q.applied.length === 1 && q.applied[0].title === "상세페이지 수정" && q.applied[0].stage_id === 71, q.applied);
|
||||
check("[2g] 등록된 줄은 체크 아이콘만(말풍선 '등록됨') — 새 탭 링크, 휴지통과 같은 줄 상자",
|
||||
/등록됨/.test(d.querySelector("#pj-meet-quick tbody tr .pj-meet-quick-done").getAttribute("title")) &&
|
||||
!/등록됨/.test(d.querySelector("#pj-meet-quick tbody tr .pj-meet-quick-acts").textContent) &&
|
||||
d.querySelector("#pj-meet-quick tbody tr a.pj-meet-quick-done").getAttribute("href") === "/project/t/555" &&
|
||||
!!d.querySelector('#pj-meet-quick tbody tr .pj-meet-quick-actbox > [data-quick="delete"]'));
|
||||
check("[2g] 머리의 '제목 → …' 안내 문구 없음", !d.querySelector("#pj-meet-quick h3 small"));
|
||||
let deleted = null;
|
||||
env.route("DELETE", /\/project\/api\/tasks\/555$/, function (u) { deleted = u; return { body: { ok: true } }; });
|
||||
env.w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
const before = d.querySelectorAll("#pj-meet-quick tbody tr").length;
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="delete"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g] 등록된 작업 삭제 → 프로젝트 작업 DELETE·줄 제거", !!deleted && d.querySelectorAll("#pj-meet-quick tbody tr").length === before - 1 &&
|
||||
!d.querySelector("#pj-meet-quick tbody tr.is-done"), [deleted, before]);
|
||||
// 적용 전 줄의 × = 줄만 지움(요청 없음)
|
||||
check("[2g] 등록된 작업 삭제 → 작업 DELETE·서버 줄 삭제·줄 제거", !!deleted && q.deleted.length === 1 && !d.querySelector("#pj-meet-quick tbody tr.is-done"), [deleted, q.deleted, before]);
|
||||
const calls = env.calls.length, n = d.querySelectorAll("#pj-meet-quick tbody tr").length;
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="remove"]').click(); await settle();
|
||||
check("[2g] 적용 전 줄 × → 줄만 지움", d.querySelectorAll("#pj-meet-quick tbody tr").length === n - 1 && env.calls.length === calls);
|
||||
check("[2g] 아직 저장 안 된 빈 줄 × → 줄만 지움(요청 없음)", env.calls.length === calls && d.querySelectorAll("#pj-meet-quick tbody tr").length >= 3, [env.calls.length - calls, n]);
|
||||
}, { notifyOnFail: true });
|
||||
|
||||
// ════════════════════ [2g2] 작업 등록 — 프로젝트·섹션 목록 맨 위에서 바로 만들기 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { promptAnswer: "신규 브랜드" });
|
||||
meetServer(env);
|
||||
const q = quickServer(env);
|
||||
let madeProject = null, madeStage = null;
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [{ id: 7, name: "브랜드", parent_id: null }] } }; });
|
||||
env.route("POST", /\/project\/api\/projects$/, function (u, body) {
|
||||
madeProject = body;
|
||||
return { status: 201, body: { project: { id: 9, name: body.name, parent_id: null, owner_email: "me@test.local" } } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/projects\/9\/stages$/, function (u, body) {
|
||||
madeStage = body;
|
||||
return { status: 201, body: { stage: { id: 91, project_id: 9, name: body.name, sort_order: 0 } } };
|
||||
});
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d;
|
||||
const open = async function (kind) {
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-pick="' + kind + '"]').click(); await settle(); await wait(5); await settle();
|
||||
return Array.from(d.querySelectorAll(".pj-ctxmenu-item"));
|
||||
};
|
||||
const click = async function (items, label) {
|
||||
items.find(function (n) { return itemLabel(n) === label; }).click(); await settle(); await wait(5); await settle();
|
||||
};
|
||||
await click(await open("project"), "새 프로젝트");
|
||||
const row = function () { return d.querySelector("#pj-meet-quick tbody tr"); };
|
||||
check("[2g2] 새 프로젝트 → 이름 묻고 만들어 바로 고름(섹션은 비움)",
|
||||
madeProject && madeProject.name === "신규 브랜드" && row().querySelector('[data-pick="project"]').textContent === "신규 브랜드" &&
|
||||
row().querySelector('[data-pick="stage"]').classList.contains("is-empty"), [madeProject, row().textContent]);
|
||||
const stageItems = await open("stage");
|
||||
check("[2g2] 섹션 목록 맨 위 '새 섹션'", itemLabel(stageItems[0]) === "새 섹션", stageItems.map(itemLabel));
|
||||
await click(stageItems, "새 섹션");
|
||||
check("[2g2] 새 섹션 → 그 프로젝트에 만들고 바로 고름(서버 줄에도)", madeStage && madeStage.name === "신규 브랜드" &&
|
||||
row().querySelector('[data-pick="stage"]').textContent === "신규 브랜드" && Object.values(q.rows)[0].stage_id === 91, [madeStage, q.rows]);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_member, MEET_URL);
|
||||
meetServer(env);
|
||||
quickServer(env);
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [{ id: 7, name: "브랜드", parent_id: null }] } }; });
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d;
|
||||
const box = d.querySelector('#pj-meet-quick tbody tr [data-pick="project"]');
|
||||
if (!box) { check("[2g2] 직원 화면 작업 등록 표", false); return; }
|
||||
box.click(); await settle(); await wait(5); await settle();
|
||||
const labels = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[2g2] 직원(User)에겐 '새 프로젝트' 없음(새 프로젝트는 Pro user 이상)", labels.indexOf("새 프로젝트") < 0 && labels.indexOf("브랜드") >= 0, labels);
|
||||
});
|
||||
|
||||
// ════════════════════ [2g3] 작업 등록 = 주차별 서버 표 · 다른 사람 줄도 보임 · 제목 "N주차 작업 등록" · 브라우저 예전 표는 서버로 ════════════════════
|
||||
await section(async function () {
|
||||
// 제목 — 입력칸(등록 전) 또는 등록된 줄의 제목 버튼·글자
|
||||
const titleOf = function (tr) { const i = tr.querySelector('input[data-field="title"]'); return i ? i.value : (tr.querySelector(".pj-meet-quick-open") || {}).textContent || ""; };
|
||||
const titles = function (d) { return Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).map(titleOf); };
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
quickServer(env, { rows: [
|
||||
{ id: 1, title: "다른 사람이 적은 줄", created_by: "bob@test.local" },
|
||||
{ id: 2, title: "다른 사람이 등록한 줄", task_id: 777, project_id: 7, project_name: "브랜드" },
|
||||
{ id: 3, title: "남의 프로젝트 줄", task_id: 778, project_id: 8, project_name: "(볼 수 없는 프로젝트)", visible: false },
|
||||
{ id: 4, title: "다른 주차 줄", week: "2026-10-05" }] });
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d;
|
||||
check("[2g3] 제목 = 'N주차 업무 등록'", /^4주차 업무 등록/.test(d.querySelector("#pj-meet-quick h3").textContent.trim()), d.querySelector("#pj-meet-quick h3").textContent);
|
||||
const ts = titles(d);
|
||||
check("[2g3] 다른 사람이 적은·등록한 줄도 보임(이 주차만)", ts.indexOf("다른 사람이 적은 줄") >= 0 && ts.indexOf("다른 사람이 등록한 줄") >= 0 &&
|
||||
ts.indexOf("다른 주차 줄") < 0, ts);
|
||||
const hidden = Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).find(function (tr) { return titleOf(tr) === "남의 프로젝트 줄"; });
|
||||
check("[2g3] 내가 멤버가 아닌 프로젝트 줄 — 이름 가림·작업 링크·삭제 없음", /볼 수 없는 프로젝트/.test(hidden.textContent) && /등록됨/.test(hidden.querySelector(".pj-meet-quick-done").getAttribute("title")) &&
|
||||
!hidden.querySelector("a") && !hidden.querySelector('[data-quick="delete"]') && !hidden.querySelector('[data-quick="open"]'));
|
||||
// 이 브라우저에만 있던 예전 표(이 주차 키 · 이번 주면 주차 없는 예전 키) → 서버로 옮기고 지움
|
||||
for (const isNow of [false, true]) {
|
||||
const e2 = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(e2);
|
||||
const q2 = quickServer(e2);
|
||||
const me = e2.d.querySelector(".pj-wrap").dataset.me || "";
|
||||
const legacy = "pj_meet_quick:" + me, weekKey = legacy + ":2026-09-28";
|
||||
e2.w.localStorage.setItem(isNow ? legacy : weekKey, JSON.stringify([{ title: "브라우저에만 있던 줄", assignee: "", projectId: null }]));
|
||||
if (isNow) e2.d.getElementById("pj-meet-quick").dataset.now = "1";
|
||||
await boot(e2); await settle(); await wait(10); await settle();
|
||||
check("[2g3] 브라우저 예전 표 → 서버로 옮김·지움(" + (isNow ? "주차 없는 예전 키, 이번 주" : "이 주차 키") + ")",
|
||||
Object.values(q2.rows).some(function (r) { return r.title === "브라우저에만 있던 줄"; }) &&
|
||||
e2.w.localStorage.getItem(isNow ? legacy : weekKey) == null && titles(e2.d).indexOf("브라우저에만 있던 줄") >= 0, [q2.rows, titles(e2.d)]);
|
||||
}
|
||||
});
|
||||
|
||||
// ════════════════════ [2g4] 작업 칸(이미 있는 작업의 세부 작업으로) · 등록된 제목 = 오른쪽 작업 창 · [크게 열기] ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
const q = quickServer(env, { rows: [{ id: 1, title: "배너 시안", project_id: 7, project_name: "브랜드", stage_id: 71, stage_name: "할 일" }] });
|
||||
env.route("GET", /\/project\/api\/projects\/7\/tasks$/, function () { return { body: { tasks: [
|
||||
{ id: 300, title: "상세페이지 리뉴얼", project_id: 7, stage_id: 71 },
|
||||
{ id: 301, title: "다른 섹션 작업", project_id: 7, stage_id: 72 },
|
||||
{ id: 302, title: "끝난 작업", project_id: 7, stage_id: 71, completed_at: "2026-09-01T00:00:00+09:00" },
|
||||
{ id: 303, title: "이미 세부 작업", project_id: 7, stage_id: null, parent_task_id: 300 }] } }; });
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d;
|
||||
const row = function () { return d.querySelector("#pj-meet-quick tbody tr"); };
|
||||
check("[2g4] 표 머리에 '업무' 칸, 예전 ↳(줄 세부 작업) 버튼 없음",
|
||||
Array.from(d.querySelectorAll("#pj-meet-quick thead th")).map(function (t) { return t.textContent; }).indexOf("업무") === 4 &&
|
||||
!d.querySelector('[data-quick="add-sub"]'));
|
||||
row().querySelector('[data-pick="task"]').click(); await settle(); await wait(5); await settle();
|
||||
const labels = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[2g4] 작업 칸 목록 = '새 업무(섹션에)' + 그 섹션의 진행 중 메인 작업만", labels[0] === "새 업무 (‘할 일’ 섹션에)" &&
|
||||
labels.indexOf("상세페이지 리뉴얼") >= 0 && labels.indexOf("다른 섹션 작업") < 0 && labels.indexOf("끝난 작업") < 0 && labels.indexOf("이미 세부 작업") < 0, labels);
|
||||
Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (n) { return itemLabel(n) === "상세페이지 리뉴얼"; }).click();
|
||||
await settle(); await wait(5); await settle();
|
||||
check("[2g4] 작업을 고르면 ↳ 표시·섹션 '—'·제목 칸 '세부 업무 제목'·서버 줄에 parent_task_id",
|
||||
/↳ 상세페이지 리뉴얼/.test(row().querySelector('[data-pick="task"]').textContent) && /—/.test(row().children[3].textContent) &&
|
||||
row().querySelector('input[data-field="title"]').placeholder === "세부 업무 제목" && q.rows[1].parent_task_id === 300, q.rows[1]);
|
||||
row().querySelector('[data-quick="apply"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g4] 적용 → 서버 [적용](고른 작업 밑 세부 작업)", q.applied.length === 1 && q.applied[0].parent_task_id === 300, q.applied);
|
||||
// 등록된 줄 — 제목을 누르면 오른쪽 작업 창(iframe, embed). 저장 확인이 '계속 편집'이면 닫히지 않음
|
||||
const open = row().querySelector('[data-quick="open"]');
|
||||
check("[2g4] 등록된 줄 제목 = 작업 창 열기 버튼", !!open && open.textContent === "배너 시안");
|
||||
open.click(); await settle();
|
||||
const panel = d.body.querySelector(".pj-meet-task-panel");
|
||||
check("[2g4] 오른쪽 작업 창(body 에) = /project/t/{id}?embed=1", !!panel && panel.classList.contains("is-open") &&
|
||||
panel.querySelector("iframe").getAttribute("src") === "/project/t/555?embed=1");
|
||||
let answer = false;
|
||||
panel.querySelector("iframe").contentWindow.__pjEmbedSettle = function () { return Promise.resolve(answer); };
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[2g4] 작업 창 저장 실패에 '계속 편집' → 창 그대로", panel.classList.contains("is-open"));
|
||||
answer = true;
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[2g4] 저장이 끝나면 Esc 로 닫힘", !panel.classList.contains("is-open"));
|
||||
// 크게 열기 — 같은 표가 넓은 창으로(줄 그대로), Esc 로 제자리
|
||||
const nRows = d.querySelectorAll("#pj-meet-quick tbody tr").length;
|
||||
d.querySelector('#pj-meet-quick [data-quick="expand"]').click(); await settle();
|
||||
const modal = d.body.querySelector(".pj-meet-quick-modal");
|
||||
check("[2g4] 크게 열기 → 같은 표를 넓은 창으로(제목 'N주차 업무 등록')", !!modal && /4주차 업무 등록/.test(modal.querySelector("h3").textContent) &&
|
||||
modal.querySelectorAll("tbody tr").length === nRows && nRows > 0);
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); await settle();
|
||||
check("[2g4] Esc → 닫히고 표는 제자리", !d.body.querySelector(".pj-meet-quick-modal") && !!d.querySelector("#pj-meet-quick table.pj-meet-quick-table"));
|
||||
});
|
||||
|
||||
// ════════════════════ [2h] 회의록은 누구나 수정 · [회의 완료](관리자)면 잠금 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_member, MEET_URL);
|
||||
@@ -996,18 +1210,23 @@ function meetServer(env, st) {
|
||||
const request = env.calls.find(c => /\/meeting-cells\/merge$/.test(c.url));
|
||||
check("[회의록 병합] 선택한 주의 줄 ID로 요청", request.body.item_from === "2" && request.body.item_to === "3");
|
||||
env.route("POST", /\/meeting-cells\/merge$/, () => ({ body: { ok: true } }));
|
||||
const gets0 = st.gets || 0;
|
||||
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(n => itemLabel(n).startsWith("셀 병합")).click(); await settle();
|
||||
check("[회의록 병합] 저장 성공 뒤 화면을 다시 받음", env.navigations === 1);
|
||||
await wait(20); await settle();
|
||||
check("[회의록 병합] 저장 성공 뒤 표만 다시 받음(새로고침 없음)", env.navigations === 0 && st.gets === gets0 + 1, [env.navigations, st.gets]);
|
||||
});
|
||||
|
||||
await section(async function () {
|
||||
const env = makeEnv(fs.readFileSync(path.join(OUT, "meeting_merged.html"), "utf8"), MEET_URL); meetServer(env); await boot(env);
|
||||
const env = makeEnv(fs.readFileSync(path.join(OUT, "meeting_merged.html"), "utf8"), MEET_URL); const st = meetServer(env); await boot(env);
|
||||
const gets0 = st.gets || 0;
|
||||
const a = env.d.querySelector('td[data-meet-item="2"]');
|
||||
check("[회의록 병합 화면] 첫 셀만 표시하고 숫자 칸 유지", a.rowSpan === 2 && !env.d.querySelector('td[data-meet-item="3"]') && env.d.querySelectorAll('.pj-meet-amount[data-field="target_amount"]').length === 3);
|
||||
a.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(n => itemLabel(n) === "병합 해제").click(); await settle();
|
||||
check("[회의록 병합 해제] 첫 셀 ID로 요청하고 화면 갱신", env.calls.some(c => c.method === "DELETE" && /\/meeting-items\/2\/cell-merge$/.test(c.url)) && env.navigations === 1);
|
||||
await wait(20); await settle();
|
||||
check("[회의록 병합 해제] 첫 셀 ID로 요청하고 표만 다시 받음", env.calls.some(c => c.method === "DELETE" && /\/meeting-items\/2\/cell-merge$/.test(c.url)) &&
|
||||
env.navigations === 0 && st.gets === gets0 + 1, [env.navigations, st.gets]);
|
||||
check("[회의록 병합 해제] 요청 중 합쳐진 글 보존", a.textContent.includes("병합한 계획"));
|
||||
});
|
||||
|
||||
@@ -1094,6 +1313,69 @@ function meetServer(env, st) {
|
||||
check("[서식 혼합] 초기화는 모든 서식 제거·내용 보존", editor.value === "작은큰");
|
||||
});
|
||||
|
||||
// ════════════════════ [2h] 항목 칸 묶음(027) — 주요 업무 칸 줄 추가는 같은 항목 칸 안에 · 표만 다시 그리며 애니메이션 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_groups, MEET_URL);
|
||||
const st = meetServer(env, { page: PAGE.meeting_groups });
|
||||
// jsdom 에는 Web Animations 가 없다 — 있는 것처럼(애니메이션 경로·새 줄 강조 확인용)
|
||||
const animated = [];
|
||||
env.w.Element.prototype.animate = function (frames) { animated.push([this, frames]); return { finished: Promise.resolve(), cancel: function () {} }; };
|
||||
const posts = [];
|
||||
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/items$/, function (u, body) {
|
||||
posts.push(body); st.page = PAGE.meeting_groups_added; return { status: 201, body: { ok: true, id: 9 } };
|
||||
});
|
||||
await boot(env);
|
||||
const gets0 = st.gets || 0;
|
||||
const head = env.d.querySelector('tr[data-item="2"] th.pj-meet-c-label');
|
||||
check("[2h] 묶음 첫 줄 항목 칸 rowspan=2 · 이어 붙은 줄은 항목 칸 없음",
|
||||
head && head.rowSpan === 2 && !env.d.querySelector('tr[data-item="3"] th.pj-meet-c-label') &&
|
||||
env.d.querySelector('tr[data-item="3"]').dataset.labelCont === "1");
|
||||
const td = env.d.querySelector('td[data-meet-item="2"]');
|
||||
td.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
let labels = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[2h] 주요 업무 칸 메뉴 — 위/아래 줄 추가 · 줄 삭제", labels.indexOf("위에 줄 추가") >= 0 && labels.indexOf("아래에 줄 추가") >= 0 &&
|
||||
labels.indexOf("줄 삭제") >= 0, labels);
|
||||
const prompts = env.prompts.length;
|
||||
const oldRow2 = env.d.querySelector('tr[data-item="2"]');
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "아래에 줄 추가"; }).click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[2h] 아래에 줄 추가 → 같은 항목 칸(same_label)·이름 안 물음", posts.length === 1 && posts[0].same_label === true &&
|
||||
String(posts[0].ref_item_id) === "2" && posts[0].place === "below" && env.prompts.length === prompts, posts);
|
||||
check("[2h] 새로고침 없이 표만 다시 받아 바꿔 끼움", env.navigations === 0 && st.gets === gets0 + 1 && !oldRow2.isConnected &&
|
||||
!!env.d.querySelector('tr[data-item="9"]'), [env.navigations, st.gets]);
|
||||
const head2 = env.d.querySelector('tr[data-item="2"] th.pj-meet-c-label');
|
||||
check("[2h] 항목 칸은 그대로(rowspan 3) — 새 줄에 항목 칸 없음", head2 && head2.rowSpan === 3 &&
|
||||
!env.d.querySelector('tr[data-item="9"] th.pj-meet-c-label'));
|
||||
const row9 = env.d.querySelector('tr[data-item="9"]');
|
||||
check("[2h] 새 줄 — 내려오며 나타나고 잠깐 강조", row9.classList.contains("is-new-row") &&
|
||||
animated.some(function (a) { return a[0] === row9 && a[1][0].opacity === 0; }));
|
||||
// 다시 끼운 칸도 저장이 연결됨(새 줄 주요 업무 입력 → 그 줄로 PUT)
|
||||
const ta9 = row9.querySelector(".pj-meet-text");
|
||||
ta9.focus(); type(env, ta9, "새 줄 업무"); ta9.blur();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[2h] 다시 끼운 새 줄도 저장 연결", st.items[9] && st.items[9].content === "새 줄 업무", st.items[9]);
|
||||
// 항목 칸 메뉴(묶음) — 순서 대신 항목 칸 나누기, 아래 추가는 묶음 맨 아래 줄 기준(항목 칸 밖에 따로)
|
||||
env.d.querySelector('tr[data-item="2"] th.pj-meet-c-label').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
labels = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[2h] 묶인 항목 칸 메뉴 — 항목 칸 나누기·첫 줄 삭제(위로·아래로 없음)", labels.indexOf("항목 칸 나누기") >= 0 &&
|
||||
labels.indexOf("첫 줄 삭제") >= 0 && labels.indexOf("위로") < 0 && labels.indexOf("아래로") < 0, labels);
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "아래에 줄 추가"; }).click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[2h] 항목 칸에서 아래 줄 추가 → 묶음 맨 아래 줄(3) 기준·따로(같은 항목 아님)·이름 물음",
|
||||
posts.length === 2 && String(posts[1].ref_item_id) === "3" && !posts[1].same_label && env.prompts.length === prompts + 1, posts[1]);
|
||||
// 이어 붙은 줄의 주요 업무 칸 → 줄 삭제(흐려지며 사라진 뒤 다시 그림)
|
||||
let deleted = null;
|
||||
env.route("DELETE", /\/project\/api\/goals\/meeting-items\/\d+$/, function (u) { deleted = u; return { body: { ok: true } }; });
|
||||
const gets = st.gets;
|
||||
const row3 = env.d.querySelector('tr[data-item="3"]');
|
||||
row3.querySelector('td[data-meet-item="3"]').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "줄 삭제"; }).click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[2h] 주요 업무 칸 줄 삭제 → 그 줄 DELETE · 흐려짐 · 표 다시 받음",
|
||||
/\/meeting-items\/3$/.test(deleted || "") && animated.some(function (a) { return a[0] === row3 && a[1][1].opacity === 0; }) &&
|
||||
st.gets === gets + 1 && env.navigations === 0, [deleted, st.gets]);
|
||||
});
|
||||
|
||||
clearTimeout(WATCHDOG);
|
||||
const realUnhandled = unhandled.filter(function (m) { return !/Not implemented/.test(m); });
|
||||
check("처리 안 된 Promise 거부 없음", realUnhandled.length === 0, realUnhandled);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// 긴급 공지 화면(static/erp-notice.js) — jsdom. 가운데 창·차례대로·[확인] 전엔 안 닫힘·확인 실패 유지·다른 곳 확인 반영.
|
||||
// NODE_PATH=<jsdom 경로> node tests/js/notice_ui.test.js
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "erp-notice.js"), "utf8");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 30) return r(); setImmediate(s); })(); }); };
|
||||
|
||||
function env(opts) {
|
||||
const dom = new JSDOM("<!doctype html><body><main>화면</main></body>", { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/cupang/" });
|
||||
const w = dom.window;
|
||||
w.__ERP_NOTICE_TEST__ = true;
|
||||
const e = { w: w, d: w.document, calls: [], pending: opts.pending, ackStatus: 200 };
|
||||
w.fetch = async function (url, o) {
|
||||
const method = (o && o.method) || "GET";
|
||||
e.calls.push(method + " " + url);
|
||||
if (url === "/notice/api/pending") {
|
||||
if (opts.status) return { ok: false, status: opts.status, json: async function () { return {}; } };
|
||||
return { ok: true, status: 200, json: async function () { return { notices: e.pending }; } };
|
||||
}
|
||||
const m = /^\/notice\/api\/(\d+)\/ack$/.exec(url);
|
||||
if (m) {
|
||||
if (e.ackStatus >= 400) return { ok: false, status: e.ackStatus, json: async function () { return {}; } };
|
||||
e.pending = e.pending.filter(function (n) { return String(n.id) !== m[1]; });
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true }; } };
|
||||
}
|
||||
return { ok: true, status: 200, json: async function () { return {}; } };
|
||||
};
|
||||
w.eval(JS);
|
||||
return e;
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const N = function (id, title, body) { return { id: id, title: title, body_html: body || "", show_at: "2026-10-12T18:00+09:00", created_by: "king@dbxcorp.co.kr" }; };
|
||||
{
|
||||
const e = env({ pending: [N(1, "서버 점검", '<p>오늘 <b>18시</b></p><img src="/notice/images/3">'), N(2, "두 번째")] });
|
||||
await settle();
|
||||
const box = e.d.querySelector(".erp-notice-backdrop");
|
||||
check("[공지] 받을 공지가 있으면 body 에 가운데 창(배율 밖)", !!box && box.parentElement === e.d.body && !box.hidden);
|
||||
check("[공지] 제목·본문(서버가 정리한 HTML)·보낸 사람·시각·1/2",
|
||||
box.querySelector(".erp-notice-title").textContent === "서버 점검" && !!box.querySelector(".erp-notice-body b") &&
|
||||
!!box.querySelector('.erp-notice-body img[src="/notice/images/3"]') &&
|
||||
/King · 10\/12 18:00/.test(box.querySelector(".erp-notice-meta").textContent) &&
|
||||
box.querySelector(".erp-notice-count").textContent === "1 / 2");
|
||||
check("[공지] [확인]에 포커스", e.d.activeElement === box.querySelector(".erp-notice-ok"));
|
||||
box.dispatchEvent(new e.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
|
||||
box.click();
|
||||
check("[공지] Esc·바깥 클릭으로 닫히지 않음", !box.hidden && box.querySelector(".erp-notice-title").textContent === "서버 점검");
|
||||
e.ackStatus = 500;
|
||||
box.querySelector(".erp-notice-ok").click(); await settle();
|
||||
check("[공지] 확인 저장 실패 — 창 유지·안내·다시 누를 수 있음", !box.hidden && !box.querySelector(".erp-notice-error").hidden &&
|
||||
!box.querySelector(".erp-notice-ok").disabled && box.querySelector(".erp-notice-title").textContent === "서버 점검");
|
||||
e.ackStatus = 200;
|
||||
box.querySelector(".erp-notice-ok").click(); await settle();
|
||||
check("[공지] 확인 → 다음 공지(차례대로)", !box.hidden && box.querySelector(".erp-notice-title").textContent === "두 번째" &&
|
||||
e.calls.indexOf("POST /notice/api/1/ack") >= 0 && box.querySelector(".erp-notice-count").hidden);
|
||||
// 다른 탭에서 확인 → 다음 확인 때 닫힘
|
||||
e.pending = [];
|
||||
await e.w.__erpNotice.poll(); await settle();
|
||||
check("[공지] 다른 곳에서 확인·취소되면 닫힘", box.hidden);
|
||||
}
|
||||
{
|
||||
const e = env({ pending: [], status: 503 });
|
||||
await settle();
|
||||
check("[공지] 024 미적용(503)이면 창 없이 조용히 멈춤", !e.d.querySelector(".erp-notice-backdrop") && e.w.__erpNotice.state().stopped);
|
||||
}
|
||||
console.log(fails.length ? fails.length + " FAIL" : "ALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})().catch(function (err) { console.error(err); process.exit(1); });
|
||||
@@ -0,0 +1,76 @@
|
||||
// 마감 지난 내 업무 알림(static/erp-overdue.js) — jsdom. 위쪽 알림·닫으면 1시간 쉼·새로 지난 업무는 바로·권한 없으면 멈춤.
|
||||
// NODE_PATH=<jsdom 경로> node tests/js/overdue_ui.test.js
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "erp-overdue.js"), "utf8");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 30) return r(); setImmediate(s); })(); }); };
|
||||
|
||||
function env(opts) {
|
||||
const dom = new JSDOM("<!doctype html><body><main>화면</main></body>", { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/cupang/" });
|
||||
const w = dom.window;
|
||||
w.__ERP_OVERDUE_TEST__ = true;
|
||||
const e = { w: w, d: w.document, calls: 0, tasks: opts.tasks || [], status: opts.status || 200 };
|
||||
if (opts.now) { const base = opts.now; w.Date.now = function () { return base + (e.shift || 0); }; }
|
||||
w.fetch = async function (url) {
|
||||
e.calls++;
|
||||
if (url !== "/project/api/my-overdue") return { ok: false, status: 404, json: async function () { return {}; } };
|
||||
if (e.status >= 400) return { ok: false, status: e.status, json: async function () { return {}; } };
|
||||
return { ok: true, status: 200, json: async function () { return { today: "2026-10-13", tasks: e.tasks }; } };
|
||||
};
|
||||
w.eval(JS);
|
||||
return e;
|
||||
}
|
||||
const T = function (id, title, due, extra) {
|
||||
return Object.assign({ id: id, title: title, due_date: due, project_id: 1, project_name: "P1", project_color: "#4573d2" }, extra || {});
|
||||
};
|
||||
|
||||
(async function () {
|
||||
{
|
||||
const many = [T(1, "보고서", "2026-10-10"), T(2, "세부<b>", "2026-10-12", { parent_title: "상위" })]
|
||||
.concat([3, 4, 5, 6, 7].map(function (i) { return T(i, "업무 " + i, "2026-10-11"); }));
|
||||
const e = env({ tasks: many, now: Date.UTC(2026, 9, 13, 3) });
|
||||
await settle();
|
||||
const box = e.d.querySelector(".erp-overdue");
|
||||
check("[마감 알림] 마감 지난 업무가 있으면 body 에 위쪽 알림(배율 밖)", !!box && box.parentElement === e.d.body && !box.hidden);
|
||||
check("[마감 알림] 건수·최대 5줄·나머지 '내 업무에서 보기'", /마감이 지난 내 업무 7건/.test(box.textContent) &&
|
||||
box.querySelectorAll(".erp-overdue-item").length === 5 && /그 밖에 2건/.test(box.querySelector(".erp-overdue-more").textContent));
|
||||
const first = box.querySelector(".erp-overdue-item");
|
||||
check("[마감 알림] 줄 = 업무 링크·마감일·며칠 지남", first.getAttribute("href") === "/project/t/1" && /마감 10\/10 · 3일 지남/.test(first.textContent));
|
||||
check("[마감 알림] 제목은 글자로(HTML 아님)·상위 업무 표시", !box.querySelector(".erp-overdue-item b b") && /상위: 상위/.test(box.textContent));
|
||||
const closeBtn = box.querySelector("[data-overdue-close]");
|
||||
check("[마감 알림] 닫기 버튼 = '닫기' 글자만(말풍선 없음)", closeBtn.textContent.trim() === "닫기" && !closeBtn.title && !closeBtn.dataset.tip, closeBtn.outerHTML);
|
||||
closeBtn.click(); await settle();
|
||||
check("[마감 알림] 닫기 → 숨김·1시간 쉼 기록", box.hidden && JSON.parse(e.w.localStorage.getItem("erp_overdue_snooze")).ids.length === 7);
|
||||
await e.w.__erpOverdue.poll(); await settle();
|
||||
check("[마감 알림] 1시간 안 다시 확인 — 같은 업무면 안 띄움", box.hidden);
|
||||
e.tasks = many.concat([T(8, "새로 지남", "2026-10-12")]);
|
||||
await e.w.__erpOverdue.poll(); await settle();
|
||||
check("[마감 알림] 새로 마감이 지난 업무가 생기면 바로 다시", !box.hidden && /8건/.test(box.textContent));
|
||||
box.querySelector("[data-overdue-close]").click(); await settle();
|
||||
e.shift = 60 * 60 * 1000 + 5;
|
||||
await e.w.__erpOverdue.poll(); await settle();
|
||||
check("[마감 알림] 1시간이 지나면 다시 나타남", !box.hidden);
|
||||
e.tasks = [];
|
||||
await e.w.__erpOverdue.poll(); await settle();
|
||||
check("[마감 알림] 다 완료하면 사라짐", box.hidden);
|
||||
}
|
||||
{
|
||||
const e = env({ tasks: [T(1, "x", "2026-10-10")], status: 403 });
|
||||
await settle();
|
||||
const n = e.calls;
|
||||
await e.w.__erpOverdue.poll(); await settle();
|
||||
check("[마감 알림] Project 권한 없음(403) — 창 없이 멈춤", !e.d.querySelector(".erp-overdue") && e.calls === n && e.w.__erpOverdue.state().stopped);
|
||||
}
|
||||
{
|
||||
const e = env({ tasks: [] });
|
||||
await settle();
|
||||
check("[마감 알림] 지난 업무 없으면 창 없음", !e.d.querySelector(".erp-overdue"));
|
||||
}
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})().catch(function (err) { console.error(err); process.exit(1); });
|
||||
@@ -0,0 +1,56 @@
|
||||
// 실적 수동 입력 칸 — 실제 브라우저(Chromium). 칸을 눌러 입력칸이 떠도 열 너비·행 높이가 그대로인지.
|
||||
// python tests/js/render_performance.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_manual.browser.test.js
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
(async function () {
|
||||
// 바꿔 넣는 글에 $ 가 있어도 그대로 들어가게 함수로 치환
|
||||
const css = fs.readFileSync(process.env.PERF_CSS || path.join(ROOT, "app", "static", "performance.css"), "utf8");
|
||||
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "perf_dash.html"), "utf8")
|
||||
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + css + "</style>"; })
|
||||
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + js + "</script>"; });
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
try {
|
||||
for (const width of [1400, 900]) {
|
||||
const page = await browser.newPage({ viewport: { width: width, height: 900 } });
|
||||
await page.route("**/performance/api/**", function (r) { r.fulfill({ status: 200, contentType: "application/json", body: "{}" }); });
|
||||
await page.setContent(html, { waitUntil: "load" });
|
||||
const measure = function () {
|
||||
return page.evaluate(function () {
|
||||
const ths = Array.from(document.querySelectorAll(".perf-main thead th")).map(function (th) { return Math.round(th.getBoundingClientRect().width); });
|
||||
const row = document.querySelector('td.is-manual-cell[data-manual-code="kakao"][data-date="2026-10-05"]').closest("tr");
|
||||
return { ths: ths, h: Math.round(row.getBoundingClientRect().height) };
|
||||
});
|
||||
};
|
||||
const before = await measure();
|
||||
for (const sel of ['td.is-manual-cell[data-manual-code="kakao"][data-date="2026-10-05"]',
|
||||
'td.is-manual-cell[data-manual-code="coupang"][data-date="2026-10-05"]']) {
|
||||
await page.click(sel);
|
||||
const during = await measure();
|
||||
const inp = await page.evaluate(function (s) {
|
||||
const td = document.querySelector(s), i = td.querySelector(".perf-manual-input");
|
||||
if (!i) return null;
|
||||
const a = td.getBoundingClientRect(), b = i.getBoundingClientRect();
|
||||
return { inside: b.left >= a.left - 0.5 && b.right <= a.right + 0.5 && b.top >= a.top - 0.5 && b.bottom <= a.bottom + 0.5,
|
||||
focused: document.activeElement === i, w: Math.round(b.width) };
|
||||
}, sel);
|
||||
check("[" + width + "px] " + sel.match(/code="(\w+)"/)[1] + " 칸 입력 — 열 너비 그대로", JSON.stringify(during.ths) === JSON.stringify(before.ths),
|
||||
{ before: before.ths, during: during.ths });
|
||||
check("[" + width + "px] " + sel.match(/code="(\w+)"/)[1] + " 칸 입력 — 행 높이 그대로·입력칸이 칸 안·포커스",
|
||||
during.h === before.h && inp && inp.inside && inp.focused && inp.w > 20, { h: [before.h, during.h], inp: inp });
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,256 @@
|
||||
// 실적 — 수동 입력(static/performance.js) · 열 순서 · 설정 토글 — jsdom.
|
||||
// python tests/js/render_performance.py && NODE_PATH=<jsdom 경로> node tests/js/perf_manual.test.js
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "performance.js"), "utf8");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 40) return r(); setImmediate(s); })(); }); };
|
||||
const wait = function (ms) { return new Promise(function (r) { setTimeout(r, ms); }); };
|
||||
|
||||
async function env(file) {
|
||||
const html = fs.readFileSync(path.join(OUT, file), "utf8").replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, "");
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/performance/" });
|
||||
const w = dom.window;
|
||||
const e = { w: w, d: w.document, calls: [], status: 200, alerts: [] };
|
||||
w.erpAlert = function (m) { e.alerts.push(m); return Promise.resolve(); };
|
||||
w.fetch = async function (url, o) {
|
||||
const method = (o && o.method) || "GET";
|
||||
const isForm = o && o.body && typeof o.body !== "string";
|
||||
const body = o && o.body && !isForm ? JSON.parse(o.body) : null;
|
||||
e.calls.push({ method: method, url: url, body: body, form: isForm ? o.body : null });
|
||||
if (/^\/performance\/api\/ad-spend\/naver\/details/.test(url)) {
|
||||
return { ok: true, status: 200, json: async function () {
|
||||
return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 },
|
||||
rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } };
|
||||
}
|
||||
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
|
||||
return { ok: true, status: 200, json: async function () {
|
||||
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } };
|
||||
}
|
||||
const ad = /^\/performance\/api\/ad-spend\/([^/]+)\/([\d-]+)$/.exec(url);
|
||||
if (ad) {
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true, manual: body.amount, amount: body.amount || 0 }; } };
|
||||
}
|
||||
if (e.status >= 400) return { ok: false, status: e.status, json: async function () { return { detail: "수동 입력을 쓰려면 마이그레이션 002" }; } };
|
||||
const m = /^\/performance\/api\/manual-sales\/([^/]+)\/([\d-]+)$/.exec(url);
|
||||
if (m) {
|
||||
const api = m[1] === "coupang" && m[2] === "2026-10-05" ? 50000 : m[1] === "coupang" && m[2] === "2026-10-06" ? 7000 : 0;
|
||||
const manual = body.amount == null ? null : body.amount;
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true, manual: manual, amount: manual == null ? api : manual, api_amount: api }; } };
|
||||
}
|
||||
return { ok: true, status: 200, json: async function () { return {}; } };
|
||||
};
|
||||
w.eval(JS);
|
||||
// jsdom 이 문서를 다 읽은 뒤 DOMContentLoaded 를 스스로 보낸다(직접 보내면 초기화가 두 번 됨)
|
||||
if (w.document.readyState !== "loading") w.document.dispatchEvent(new w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
return e;
|
||||
}
|
||||
function key(e, el, k, extra) { el.dispatchEvent(new e.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}))); }
|
||||
function cell(e, code, day) { return e.d.querySelector('td.is-manual-cell[data-manual-code="' + code + '"][data-date="' + day + '"]'); }
|
||||
function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
|
||||
(async function () {
|
||||
// ── 열 순서·제목 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); });
|
||||
check("[순서] 카페24·네이버·쿠팡·토스·GS샵·11번가 다음 나머지", heads.join(",") ===
|
||||
"날짜,카페24,네이버,쿠팡,토스,GS샵,11번가,오늘의집,G마켓,카카오,롯데ON,일 합계", heads);
|
||||
check("[수동] 수동 입력 쇼핑몰 제목에 ✎ 표시", /✎/.test(e.d.querySelectorAll(".perf-main thead th")[3].textContent) &&
|
||||
!/✎/.test(e.d.querySelectorAll(".perf-main thead th")[1].textContent));
|
||||
check("[수동] 오늘까지 날짜 칸만 입력 칸(앞으로의 날·주간합계 아님), 수동 값 칸은 파란 표시",
|
||||
!!cell(e, "coupang", "2026-10-07") && !cell(e, "coupang", "2026-10-08") && cell(e, "coupang", "2026-10-05").classList.contains("is-manual") &&
|
||||
!cell(e, "coupang", "2026-10-06").classList.contains("is-manual") && !e.d.querySelector(".perf-row-week td.is-manual-cell"));
|
||||
check("[수동] 입력 칸은 주문 상세 링크가 아님", !cell(e, "coupang", "2026-10-06").classList.contains("is-link") &&
|
||||
e.d.querySelector('td.is-link[data-code="cafe24"]') !== null);
|
||||
check("[수동] 표 아래 사용법 안내", /직접 입력/.test((e.d.querySelector(".perf-manual-help") || {}).textContent || ""));
|
||||
}
|
||||
// ── 입력 → Enter 저장 후 아래 칸 → Esc 끝 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
let reloaded = 0;
|
||||
const td5 = cell(e, "coupang", "2026-10-05");
|
||||
td5.click();
|
||||
const in5 = td5.querySelector(".perf-manual-input");
|
||||
check("[입력] 칸을 누르면 입력칸(수동 값이 들어 있음)", !!in5 && in5.value === "87000" && e.d.activeElement === in5);
|
||||
in5.value = "90,000원";
|
||||
key(e, in5, "Enter");
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[입력] Enter → 그 칸 저장(쉼표·원 빼고 숫자)", put && put.url === "/performance/api/manual-sales/coupang/2026-10-05" && put.body.amount === 90000, e.calls);
|
||||
check("[입력] 저장한 값 표시 + 아래 칸(10/6)으로 입력칸 이동", gross(td5) === "90,000" && !td5.querySelector(".perf-manual-input") &&
|
||||
!!cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input"));
|
||||
const in6 = cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input");
|
||||
check("[입력] 수동 값 없는 칸은 비어 있고 API 값이 흐리게(placeholder)", in6.value === "" && in6.placeholder === "7,000", in6.placeholder);
|
||||
key(e, in6, "Enter"); // 아무것도 안 넣고 Enter — 저장 안 함
|
||||
await settle();
|
||||
check("[입력] 빈 칸 그대로 Enter → 저장 요청 없음", e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1);
|
||||
const in7 = cell(e, "coupang", "2026-10-07").querySelector(".perf-manual-input");
|
||||
check("[입력] 마지막 입력 칸(오늘)까지 이동", !!in7);
|
||||
in7.value = "abc";
|
||||
key(e, in7, "Enter");
|
||||
await settle(); await wait(200); await settle();
|
||||
check("[입력] 숫자가 아니면 저장 안 하고 안내", e.alerts.some(function (m) { return /숫자/.test(m); }) &&
|
||||
e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1, e.alerts);
|
||||
}
|
||||
// ── 수동 값 지우기(비우고 저장) → API 값, 실패 시 안내 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const td5 = cell(e, "coupang", "2026-10-05");
|
||||
td5.click();
|
||||
const inp = td5.querySelector(".perf-manual-input");
|
||||
inp.value = "";
|
||||
key(e, inp, "Escape");
|
||||
check("[지우기] Esc → 저장 없이 닫힘", !td5.querySelector(".perf-manual-input") && !e.calls.some(function (c) { return c.method === "PUT"; }));
|
||||
td5.click();
|
||||
const inp2 = td5.querySelector(".perf-manual-input");
|
||||
inp2.value = "";
|
||||
inp2.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[지우기] 비우고 칸을 떠나면 amount=null(그날 API 값)", put && put.body.amount === null);
|
||||
check("[지우기] API 값(50,000) 표시·파란 표시 해제", gross(td5) === "50,000" && !td5.classList.contains("is-manual"));
|
||||
e.status = 503;
|
||||
const td6 = cell(e, "coupang", "2026-10-06");
|
||||
td6.click();
|
||||
const i6 = td6.querySelector(".perf-manual-input");
|
||||
i6.value = "100";
|
||||
i6.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
check("[실패] 저장 실패 → 안내(마이그레이션), 값은 그대로", e.alerts.some(function (m) { return /마이그레이션 002/.test(m); }) && gross(td6) === "7,000", e.alerts);
|
||||
}
|
||||
// ── 키보드: 칸에서 Enter 로 입력 시작 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const td = cell(e, "kakao", "2026-10-06");
|
||||
td.focus();
|
||||
key(e, td, "Enter");
|
||||
check("[키보드] 칸에 포커스 후 Enter → 입력칸", !!td.querySelector(".perf-manual-input"));
|
||||
}
|
||||
// ── 탭: [매출 실적] [광고비] + 맨 오른쪽 설정 톱니 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const tabs = Array.from(e.d.querySelectorAll(".perf-tabs-main .perf-tab")).map(function (a) { return a.textContent.replace(/monitoring|campaign/, "").trim(); });
|
||||
check("[탭] 매출 실적 · 광고비", tabs.join(",") === "매출 실적,광고비", tabs);
|
||||
check("[탭] 매출 실적이 고른 탭", e.d.querySelector(".perf-tab-sales").classList.contains("is-active") &&
|
||||
!e.d.querySelector(".perf-tab-ads").classList.contains("is-active"));
|
||||
const gear = e.d.querySelector(".perf-tabs > .perf-tab-gear");
|
||||
check("[탭] 설정 = 맨 오른쪽 톱니 아이콘(settings)", gear && gear === e.d.querySelector(".perf-tabs").lastElementChild &&
|
||||
gear.getAttribute("href") === "/performance/settings" && gear.textContent.trim() === "settings" && !!gear.title);
|
||||
}
|
||||
// ── 광고비 화면 ──
|
||||
{
|
||||
const e = await env("perf_ads.html");
|
||||
check("[광고비] 광고비 탭이 고른 탭", e.d.querySelector(".perf-tab-ads").classList.contains("is-active"));
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").replace("table_view", "").trim(); });
|
||||
check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰",
|
||||
heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,일 합계", heads);
|
||||
const wing = cell(e, "coupang_wing", "2026-10-05");
|
||||
check("[광고비] 칸 = 광고비(ROAS%) — 쿠팡(윙) 29,000 · 쿠팡 매출 87,000 → 300%",
|
||||
wing.textContent.trim() === "29,000(300%)" && !cell(e, "naver", "2026-10-05").querySelector(".perf-roas"), wing.textContent);
|
||||
const up = cell(e, "coupang_rocket", "2026-10-01"), man = cell(e, "google", "2026-10-02");
|
||||
check("[광고비] 업로드 값 = 주황(is-upload), 직접 입력 = 파랑(is-manual)", up.classList.contains("is-upload") &&
|
||||
!up.classList.contains("is-manual") && man.classList.contains("is-manual") && gross(up) === "220,000");
|
||||
check("[광고비] 앞으로의 날은 입력 칸 아님", !cell(e, "google", "2026-10-08") && !!cell(e, "google", "2026-10-07"));
|
||||
const kpi = Array.from(e.d.querySelectorAll(".perf-kpi-value")).map(function (n) { return n.textContent.trim(); });
|
||||
check("[광고비] KPI — 이번달 광고비 599,000(네이버 300,000 포함) · 매출 대비 비율", kpi[0] === "₩599,000" && /%$/.test(kpi[1]), kpi);
|
||||
wing.click();
|
||||
const wi = wing.querySelector(".perf-manual-input");
|
||||
wi.value = "30000";
|
||||
wi.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
check("[광고비] 광고비를 고치면 옛 ROAS 는 지움(새로고침 때 다시 계산)", gross(wing) === "30,000" && !wing.querySelector(".perf-roas"));
|
||||
e.calls.length = 0;
|
||||
check("[광고비] 매출 실적의 수수료 전환 없음", !e.d.querySelector(".perf-metric") && e.d.getElementById("perf-dash").dataset.metric === "gross");
|
||||
const td = cell(e, "meta", "2026-10-03");
|
||||
td.click();
|
||||
const inp = td.querySelector(".perf-manual-input");
|
||||
check("[광고비] 칸을 누르면 입력칸(광고비)", !!inp && /광고비/.test(inp.getAttribute("aria-label")));
|
||||
inp.value = "33,000";
|
||||
key(e, inp, "Escape");
|
||||
td.click();
|
||||
const inp2 = td.querySelector(".perf-manual-input");
|
||||
inp2.value = "33,000";
|
||||
inp2.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[광고비] 저장 → /api/ad-spend/meta/2026-10-03 (33000)", put && put.url === "/performance/api/ad-spend/meta/2026-10-03" &&
|
||||
put.body.amount === 33000, e.calls);
|
||||
check("[광고비] 저장 후 파란 표시", gross(td) === "33,000" && td.classList.contains("is-manual"));
|
||||
// 파일 업로드 창
|
||||
e.d.getElementById("perf-ad-upload").click();
|
||||
const modal = e.d.querySelector(".perf-modal");
|
||||
const opts = Array.from(modal.querySelectorAll(".perf-ad-channel option")).map(function (o) { return o.value; });
|
||||
check("[업로드] 채널 선택 = 양식이 정해진 네이버·쿠팡(윙)·쿠팡(로켓)", opts.join(",") === "naver,coupang_wing,coupang_rocket", opts);
|
||||
check("[업로드] 네이버 안내 = 3열 기간·4열 총비용·12열 ROAS", /3열 기간.*4열 총비용.*12열/.test(modal.querySelector(".perf-ad-help").textContent));
|
||||
modal.querySelector(".perf-ad-channel").value = "coupang_rocket";
|
||||
modal.querySelector(".perf-ad-channel").dispatchEvent(new e.w.Event("change"));
|
||||
check("[업로드] 양식 안내(19열 청구금액)", /19열/.test(modal.querySelector(".perf-ad-help").textContent));
|
||||
const fileInput = modal.querySelector(".perf-upload-file");
|
||||
check("[업로드] 파일 여러 개 고르기", fileInput.multiple === true);
|
||||
const f = new e.w.File(["날짜"], "rocket.csv", { type: "text/csv", lastModified: 1700000000000 });
|
||||
const f2 = new e.w.File(["날짜"], "rocket2.csv", { type: "text/csv", lastModified: 1800000000000 });
|
||||
Object.defineProperty(fileInput, "files", { value: [f, f2] });
|
||||
Array.from(modal.querySelectorAll(".perf-modal-foot button, button")).filter(function (b) { return b.textContent === "업로드"; })[0].click();
|
||||
await settle();
|
||||
const post = e.calls.find(function (c) { return c.method === "POST"; });
|
||||
check("[업로드] POST /api/ad-spend/upload?channel=coupang_rocket (파일)", post && post.url === "/performance/api/ad-spend/upload?channel=coupang_rocket" && !!post.form, e.calls);
|
||||
check("[업로드] 파일마다 files + 파일 날짜(modified)", post && post.form.getAll("files").length === 2 &&
|
||||
JSON.stringify(post.form.getAll("modified")) === JSON.stringify(["1700000000000", "1800000000000"]), post && post.form.getAll("modified"));
|
||||
check("[업로드] 끝나면 창이 닫힘", !e.d.body.contains(modal) && !e.d.querySelector(".perf-modal"));
|
||||
// 금액이 없던 날짜가 있으면 창을 두고 알려 준다
|
||||
e.uploadEmpty = ["2026-03-02"];
|
||||
e.d.getElementById("perf-ad-upload").click();
|
||||
const modal2 = e.d.querySelector(".perf-modal");
|
||||
Object.defineProperty(modal2.querySelector(".perf-upload-file"), "files", { value: [f] });
|
||||
Array.from(modal2.querySelectorAll("button")).filter(function (b) { return b.textContent === "업로드"; })[0].click();
|
||||
await settle();
|
||||
check("[업로드] 청구금액 없던 날짜가 있어도 넘어가고 창 닫힘", !e.d.body.contains(modal2), modal2.textContent);
|
||||
}
|
||||
// ── 네이버 — 보고서 ROAS 표시 · 머리글 → 일자별 보고서 항목 ──
|
||||
{
|
||||
const e = await env("perf_ads.html");
|
||||
const nv = cell(e, "naver", "2026-10-03");
|
||||
check("[네이버] 칸 = 광고비(보고서 ROAS 반올림)", nv.textContent.trim() === "300,000(251%)", nv.textContent);
|
||||
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
|
||||
check("[네이버] 머리글 = 상세 보기 버튼(다른 채널은 아님)", !!hb && e.d.querySelectorAll(".perf-main thead [data-detail-channel]").length === 1);
|
||||
hb.click(); await settle();
|
||||
const call = e.calls.find(function (c) { return /\/details/.test(c.url); });
|
||||
check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);
|
||||
const modal = e.d.querySelector(".perf-modal");
|
||||
const ths = Array.from(modal.querySelectorAll("thead th")).map(function (t) { return t.textContent; });
|
||||
const row = Array.from(modal.querySelectorAll("tbody tr")[0].children).map(function (t) { return t.textContent; });
|
||||
check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" &&
|
||||
row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]);
|
||||
check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent));
|
||||
}
|
||||
// ── 설정: 수동 입력 토글 ──
|
||||
{
|
||||
const e = await env("perf_settings.html");
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-set-table thead th")).map(function (th) { return th.textContent.trim(); });
|
||||
check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads);
|
||||
const rows = Array.from(e.d.querySelectorAll(".perf-set-table tbody tr")).map(function (tr) { return tr.dataset.code; });
|
||||
check("[설정] 쇼핑몰 순서 = 어댑터 등록 순서(003 열 순서)", rows.join(",") === "cafe24,naver,coupang,ohouse,gmarket,kakao,gsshop,elevenst,lotteon,toss", rows);
|
||||
const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]');
|
||||
check("[설정] 켜진 쇼핑몰은 체크", box && box.checked && !e.d.querySelector('tr[data-code="cafe24"] input[data-field="manual_input"]').checked);
|
||||
box.checked = false;
|
||||
box.dispatchEvent(new e.w.Event("change", { bubbles: true }));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[설정] 토글 → 바로 저장(manual_input)", put && put.url === "/performance/api/marketplaces/coupang" && put.body.manual_input === false, e.calls);
|
||||
e.status = 503;
|
||||
const box2 = e.d.querySelector('tr[data-code="naver"] input[data-field="manual_input"]');
|
||||
box2.checked = true;
|
||||
box2.dispatchEvent(new e.w.Event("change", { bubbles: true }));
|
||||
await settle();
|
||||
check("[설정] 저장 실패(002 미적용) → 되돌리고 안내", !box2.checked && e.alerts.some(function (m) { return /마이그레이션/.test(m); }), e.alerts);
|
||||
}
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
+240
-4
@@ -17,6 +17,7 @@ const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
|
||||
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
|
||||
const mytasksHtml = fs.readFileSync(path.join(__dirname, ".out", "mytasks_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
@@ -235,7 +236,7 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
d.getElementById("pj-t-priority").value = "high";
|
||||
d.getElementById("pj-t-priority").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
await wait(10); d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[10] 저장 중 Esc → 저장이 끝날 때까지 창 유지", !modal.hidden);
|
||||
env.setConfirm(true); // 버리고 넘어가기
|
||||
const opening = P.openTaskModal(taskOf(P, 102)); await settle();
|
||||
@@ -433,7 +434,16 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
env.route("POST", /projects\/1\/tasks$/, function () { return pending.promise; });
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await wait(10);
|
||||
let input = d.querySelector(".pj-tasknew-title");
|
||||
check("[board] 추가는 상세창 대신 이름·담당자·마감일 카드", input && d.getElementById("pj-modal-task").hidden && d.querySelectorAll(".pj-tasknew input").length === 1 && d.querySelectorAll(".pj-tasknew-meta button").length === 2);
|
||||
check("[board] 추가는 상세창 대신 이름·담당자·협업자·마감일 카드", input && d.getElementById("pj-modal-task").hidden && d.querySelectorAll(".pj-tasknew input").length === 1 &&
|
||||
Array.from(d.querySelectorAll(".pj-tasknew-meta button")).map(function (b) { return b.className; }).join(",") === "pj-tasknew-assignee,pj-tasknew-fol,pj-tasknew-due");
|
||||
// 협업자(담당자 옆) — 고르면 아이콘이 바뀌고, 만들 때 followers 로 같이 보낸다
|
||||
d.querySelector(".pj-tasknew-fol").click(); await settle();
|
||||
const folPick = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /me/i.test(b.textContent); });
|
||||
if (folPick) folPick.click();
|
||||
await settle();
|
||||
await wait(10); d.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
check("[board] 협업자 고르면 카드에 표시", !!folPick && /협업자: Me/i.test(d.querySelector(".pj-tasknew-fol").title), d.querySelector(".pj-tasknew-fol").title);
|
||||
input.value = "간단한 새 작업"; input.dispatchEvent(new w.Event("input"));
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true })); await settle();
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", keyCode: 229, bubbles: true })); await settle();
|
||||
@@ -446,12 +456,13 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", bubbles: true })); await settle();
|
||||
check("[board] 보드 다시 그리는 중에도 저장 상태 유지", input.disabled && input.value === "간단한 새 작업" && posts().length === 1);
|
||||
check("[board] 생성 요청은 현재 섹션과 세 필드만", Object.keys(posts()[0].body).sort().join(",") === "assignee_email,assignee_name,due_date,stage_id,title" && posts()[0].body.stage_id === 11);
|
||||
check("[board] 생성 요청은 현재 섹션과 이름·담당자·협업자·마감일만", Object.keys(posts()[0].body).sort().join(",") === "assignee_email,assignee_name,due_date,followers,stage_id,title" &&
|
||||
posts()[0].body.stage_id === 11 && JSON.stringify(posts()[0].body.followers) === '["me@test.local"]', posts()[0].body);
|
||||
pending.resolve({ body: { task: detail(801, "간단한 새 작업") } }); await settle(); await wait(10);
|
||||
check("[board] Enter 저장 후 새 카드와 다음 빈 입력 유지", !!d.querySelector('.pj-card[data-task-id="801"]') && d.querySelector(".pj-tasknew-title").value === "");
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[board] Esc는 입력 카드만 취소", !d.querySelector(".pj-tasknew") && posts().length === 1);
|
||||
check("[board] Esc는 입력 카드만 취소", !d.querySelector(".pj-tasknew") && posts().length === 1, [!!d.querySelector(".pj-tasknew"), posts().length, posts().map(function (p) { return p.body.title; })]);
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await settle();
|
||||
d.body.dispatchEvent(new w.Event("pointerdown", { bubbles: true })); await wait(10); await settle();
|
||||
check("[board] 빈 카드 바깥 클릭은 빈 작업 생성 없이 닫기", !d.querySelector(".pj-tasknew") && posts().length === 1);
|
||||
@@ -719,8 +730,20 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
// 막대 = 그 작업 전체, 채움 = 완료율(작업 수가 아니라) — Me 메인 1/2 → 50%, 하위 1/1 → 100%, Bob 0/1 → 0%
|
||||
const pcts = Array.from(env.d.querySelectorAll(".pj-wl-done")).map(function (f) { return f.dataset.pct; });
|
||||
check("[대시보드 담당자별] 채움 높이 = 완료율", JSON.stringify(pcts) === JSON.stringify(["50", "50", "0", "0"]), pcts);
|
||||
check("[대시보드 담당자별] 이름 왼쪽 프로필 아이콘", Array.from(env.d.querySelectorAll(".pj-wl-name")).every(function (n) {
|
||||
const av = n.querySelector(".pj-wl-name-row > .pj-wl-avatar");
|
||||
return av && av.nextElementSibling === n.querySelector("b");
|
||||
}), env.d.querySelector(".pj-wl-name") && env.d.querySelector(".pj-wl-name").innerHTML);
|
||||
const sum = env.d.querySelector(".pj-wl-sum").textContent.replace(/\s+/g, " ");
|
||||
check("[대시보드 담당자별] 전체 완료 2/6 (33%)", /2 \/ 6 \(33%\)/.test(sum), sum);
|
||||
// 패널 날짜 = mm/dd(요일), 마감 지난 미완료만 빨간 굵은 글씨(2026-10-14)
|
||||
P.state().tasks.forEach(function (t) {
|
||||
if (t.id === 101) t.due_date = "2026-09-01"; // 완료 — 지나도 보통 글씨
|
||||
if (t.id === 102) t.due_date = "2026-09-01"; // 미완료 — 지남(화요일)
|
||||
});
|
||||
env.d.querySelectorAll(".pj-wl-group")[0].querySelector(".pj-wl-col:not(.is-sub)").click(); await settle();
|
||||
const ems = Array.from(env.d.body.querySelectorAll(".pj-wl-drawer .pj-wl-item em")).map(function (m) { return m.textContent + (m.classList.contains("is-overdue") ? "!" : ""); });
|
||||
check("[대시보드 담당자별] 패널 날짜 mm/dd(요일) + 지난 미완료만 빨강", JSON.stringify(ems) === JSON.stringify(["09/01(화)!", "09/01(화)"]), ems);
|
||||
// 막대 → 오른쪽 패널(body 에) → 항목 → 편집 창
|
||||
env.d.querySelectorAll(".pj-wl-group")[1].querySelector(".pj-wl-col.is-sub").click(); await settle();
|
||||
const drawer = env.d.body.querySelector(".pj-wl-drawer");
|
||||
@@ -730,6 +753,214 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
drawer.querySelector(".pj-wl-item").click(); await settle();
|
||||
check("[대시보드 담당자별] 항목 → 작업 편집 창(하위 작업은 서버에서 받아)", !env.d.getElementById("pj-modal-task").hidden &&
|
||||
env.d.getElementById("pj-t-title").value === "하위 2", env.d.getElementById("pj-t-title").value);
|
||||
// 목록 패널에서 연 작업 창은 패널 왼쪽에 붙는다(2026-10-13) — 패널은 그대로, 고른 줄 표시
|
||||
const tm = env.d.getElementById("pj-modal-task");
|
||||
check("[대시보드 담당자별] 작업 창 = 목록 패널 왼쪽(패널 유지·고른 줄 표시)", tm.classList.contains("pj-beside-drawer") &&
|
||||
/px$/.test(tm.style.right) && env.d.body.contains(drawer) && drawer.querySelector(".pj-wl-item.is-current") !== null,
|
||||
[tm.className, tm.style.right]);
|
||||
// 작업 창을 닫으면 대시보드는 내용만 갱신 — 패널을 닫았다 다시 열지 않고(같은 요소·is-open 유지),
|
||||
// 숫자는 0부터 다시 세지 않는다(깜박임 방지, 2026-10-13).
|
||||
await wait(10); env.d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
await wait(400); await settle();
|
||||
const drawers = env.d.body.querySelectorAll(".pj-wl-drawer");
|
||||
check("[대시보드 담당자별] 작업 창 닫기 → 같은 패널 유지(닫았다 다시 열지 않음)", tm.hidden && drawers.length === 1 &&
|
||||
drawers[0] === drawer && drawer.classList.contains("is-open") && drawer.querySelector(".pj-wl-item.is-current") !== null,
|
||||
[tm.hidden, drawers.length, drawers[0] === drawer]);
|
||||
// 같은 값으로 다시 그리면(필터 change — 값은 그대로) 그 즉시 최종 숫자(애니메이션 프레임 전에 "0" 이 아님)
|
||||
await wait(800);
|
||||
const statFinal = Array.from(env.d.querySelectorAll("#pj-dash .pj-dash-stat-value")).map(function (n) { return n.textContent; });
|
||||
env.d.getElementById("pj-fb-status").dispatchEvent(new env.w.Event("change", { bubbles: true }));
|
||||
const statNow = Array.from(env.d.querySelectorAll("#pj-dash .pj-dash-stat-value")).map(function (n) { return n.textContent; });
|
||||
check("[대시보드] 다시 그려도 숫자를 0부터 세지 않음", statNow.length === 4 && statFinal[3] !== "0" &&
|
||||
JSON.stringify(statNow) === JSON.stringify(statFinal), [statFinal, statNow]);
|
||||
// 카드 등장(투명 → 보임) 애니메이션은 탭에 들어올 때만 — 다시 그릴 때 켜지면 카드가 깜박인다
|
||||
const dashRoot = env.d.getElementById("pj-dash");
|
||||
const introOnRedraw = dashRoot.classList.contains("pj-dash-intro");
|
||||
env.d.querySelector('.pj-tab[data-view="board"]').click();
|
||||
env.d.querySelector('.pj-tab[data-view="dashboard"]').click();
|
||||
check("[대시보드] 카드 등장 애니메이션 = 탭 진입 때만", !introOnRedraw && dashRoot.classList.contains("pj-dash-intro"),
|
||||
[introOnRedraw, dashRoot.className]);
|
||||
}
|
||||
// ── 섹션 제목 오른쪽 담당자 바로 지정 · 업무 창 세부 업무 줄 협업자(2026-10-13) ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const stagePuts = [], folPosts = [];
|
||||
env.route("PUT", /\/project\/api\/projects\/1\/stages\/11$/, function (u, b) { stagePuts.push(b); return { body: { ok: true } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/1\/stages$/, function () {
|
||||
return { body: { stages: [
|
||||
{ id: 11, project_id: 1, name: "할 일", is_done_stage: false, sort_order: 0, created_by: "me@test.local", default_assignee_email: stagePuts.length ? "me@test.local" : "" },
|
||||
{ id: 12, project_id: 1, name: "완료", is_done_stage: true, sort_order: 1, created_by: "me@test.local", default_assignee_email: "" }] } };
|
||||
});
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () {
|
||||
return { body: { task: detail(101, "작업 A", { subtasks: [{ id: 901, title: "세부 하나", project_id: 1, parent_task_id: 101, followers: [] }] }) } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/tasks\/901\/followers$/, function (u, b) { folPosts.push(b); return { body: { followers: [b.email] } }; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
const head = function () { return d.querySelector('.pj-col[data-stage-id="11"] .pj-col-assignee'); };
|
||||
check("[섹션 담당자] 제목 오른쪽 빈 담당자 아이콘(눌러서 지정)", !!head() && head().classList.contains("is-editable") && head().classList.contains("is-empty"));
|
||||
head().click(); await settle();
|
||||
const pick = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /me/i.test(b.textContent) && !/없음/.test(b.textContent); });
|
||||
check("[섹션 담당자] 멤버 메뉴", !!pick);
|
||||
pick.click(); await settle(); await settle();
|
||||
check("[섹션 담당자] 고르면 섹션 PUT(default_assignee_email) 후 아이콘 갱신",
|
||||
stagePuts.length === 1 && stagePuts[0].default_assignee_email === "me@test.local" && !!head() && !head().classList.contains("is-empty"),
|
||||
[stagePuts, head() && head().className]);
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const row = function () { return d.querySelector('#pj-subtask-list .pj-subtask-row[data-id="901"]'); };
|
||||
const fol = row() && row().querySelector(".pj-subtask-fol");
|
||||
check("[세부 업무 협업자] 담당자 오른쪽에 협업자 아이콘", !!fol && !fol.hidden &&
|
||||
row().querySelector(".pj-subtask-av").nextElementSibling === fol && fol.classList.contains("is-empty"));
|
||||
fol.click(); await settle();
|
||||
const fp = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /me/i.test(b.textContent); });
|
||||
fp.click(); await settle();
|
||||
check("[세부 업무 협업자] 고르면 그 세부 업무 협업자 POST·아이콘 갱신", folPosts.length === 1 && folPosts[0].email === "me@test.local" &&
|
||||
!fol.classList.contains("is-empty"), [folPosts, fol.className]);
|
||||
check("[세부 업무 협업자] 고른 뒤 메뉴가 다시 열려 이어서 고름", !!d.querySelector(".pj-ctxmenu"));
|
||||
await wait(10); d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
}
|
||||
// ── 보드 카드 협업자(담당자 오른쪽, 마우스를 올리면 보이는 아이콘) — 눌러서 받아 오고 고르면 저장(2026-10-13) ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const posts = [];
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/followers$/, function () { return { body: { followers: [] } }; });
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/followers$/, function (u, b) { posts.push(b); return { body: { followers: [b.email] } }; });
|
||||
await boot(env); const d = env.d, w = env.w;
|
||||
const fol = function () { return d.querySelector('.pj-card[data-task-id="101"] .pj-card-meta .pj-card-fol'); };
|
||||
const av = d.querySelector('.pj-card[data-task-id="101"] .pj-card-meta .pj-card-assignee');
|
||||
check("[카드 협업자] 담당자 오른쪽 빈 협업자 아이콘(마우스를 올릴 때만 보이는 is-empty)",
|
||||
!!fol() && fol().classList.contains("is-empty") && av.nextElementSibling === fol());
|
||||
fol().click(); await settle();
|
||||
const pick = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /me/i.test(b.textContent); });
|
||||
check("[카드 협업자] 누르면 업무 창 없이 멤버 메뉴", !!pick && d.getElementById("pj-modal-task").hidden);
|
||||
pick.click(); await settle();
|
||||
await wait(10); d.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[카드 협업자] 고르면 POST·아이콘이 늘 보이게(is-empty 해제)", posts.length === 1 && posts[0].email === "me@test.local" &&
|
||||
!fol().classList.contains("is-empty"), posts);
|
||||
}
|
||||
// ── 내 업무 — 줄을 누르면 화면 이동 없이 오른쪽 업무 창(iframe), 닫으면 목록 다시 받기(2026-10-13) ──
|
||||
{
|
||||
const env = makeEnv(mytasksHtml); baseRoutes(env);
|
||||
let reloads = 0;
|
||||
env.route("GET", /\/project\/api\/my-tasks$/, function () { reloads++; return { body: { tasks: [] } }; });
|
||||
await boot(env); const d = env.d, w = env.w;
|
||||
const before = w.location.href;
|
||||
const row = d.querySelector('tr.pj-mtk-row[data-task-id="101"]');
|
||||
check("[내 업무 창] 목록 줄", !!row);
|
||||
row.querySelector(".pj-mtk-title").click(); await settle();
|
||||
const panel = d.body.querySelector(".pj-inbox-panel");
|
||||
check("[내 업무 창] 줄 클릭 → 오른쪽 업무 창(/project/t/101?embed=1), 화면 그대로·줄 표시",
|
||||
!!panel && panel.classList.contains("is-open") && /\/project\/t\/101\?embed=1$/.test(panel.querySelector("iframe").getAttribute("src")) &&
|
||||
w.location.href === before && row.classList.contains("is-panel-selected"), panel && panel.querySelector("iframe").getAttribute("src"));
|
||||
d.querySelector('tr.pj-mtk-row[data-task-id="102"]').click(); await settle();
|
||||
check("[내 업무 창] 다른 줄 → 같은 창에서 바꿈", /\/project\/t\/102\?embed=1$/.test(panel.querySelector("iframe").getAttribute("src")) &&
|
||||
!row.classList.contains("is-panel-selected"));
|
||||
const grp = d.querySelector("tr.pj-mtk-parent-group");
|
||||
if (grp) { grp.click(); await settle(); }
|
||||
check("[내 업무 창] 남의 상위 업무 줄 → 그 상위 업무를 창에", !grp || /\/project\/t\/300\?embed=1$/.test(panel.querySelector("iframe").getAttribute("src")));
|
||||
await wait(10); d.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[내 업무 창] Esc → 닫고 목록 다시 받기", !panel.classList.contains("is-open") && reloads === 1, reloads);
|
||||
}
|
||||
// ── 업무 카드를 왼쪽 프로젝트로 끌어 다른 프로젝트로 이동(2026-10-13) — 섹션 선택 창 → move-project ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const moves = [];
|
||||
env.route("GET", /\/project\/api\/projects\/2\/stages$/, function () {
|
||||
return { body: { stages: [
|
||||
{ id: 22, project_id: 2, name: "진행", is_done_stage: false, sort_order: 1 },
|
||||
{ id: 21, project_id: 2, name: "할 일", is_done_stage: false, sort_order: 0 },
|
||||
{ id: 23, project_id: 2, name: "완료", is_done_stage: true, sort_order: 2 }] } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/move-project$/, function (u, b) {
|
||||
moves.push(b); return { body: { task: detail(101, "작업 A", { project_id: 2, stage_id: b.stage_id }), unseen: [] } };
|
||||
});
|
||||
await boot(env); const d = env.d, w = env.w;
|
||||
const data = {}; const transfer = { types: [], dropEffect: "", effectAllowed: "",
|
||||
setData: function (k, v) { data[k] = v; this.types.push(k); }, getData: function (k) { return data[k] || ""; } };
|
||||
function fire(el, kind) {
|
||||
const e = new w.MouseEvent(kind, { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(e, "dataTransfer", { value: transfer });
|
||||
el.dispatchEvent(e); return e;
|
||||
}
|
||||
const card = d.querySelector('.pj-card[data-task-id="101"]');
|
||||
fire(card, "dragstart");
|
||||
check("[프로젝트 이동] 카드 드래그에 이동 종류(업무 id)", data["application/x-pj-task"] === "101" && data["text/plain"] === "101");
|
||||
const li = d.querySelector('.pj-side .pj-tree-li[data-id="2"]');
|
||||
const over = fire(li.querySelector(".pj-tree-row") || li, "dragover");
|
||||
check("[프로젝트 이동] 왼쪽 프로젝트 줄 위 — 놓기 허용·강조", over.defaultPrevented && !!li.querySelector(".pj-tree-row.is-task-drop"));
|
||||
fire(li.querySelector(".pj-tree-row") || li, "drop"); await settle(); await settle();
|
||||
const modal = d.body.querySelector(".pj-move-modal");
|
||||
const names = modal ? Array.from(modal.querySelectorAll(".pj-move-stage-name")).map(function (n) { return n.textContent; }) : [];
|
||||
check("[프로젝트 이동] 섹션 선택 창(body 에, 섹션 순서대로, 첫 진행 섹션 선택)", !!modal && modal.parentElement === d.body &&
|
||||
JSON.stringify(names) === '["할 일","진행","완료"]' && modal.querySelector("input:checked").value === "21" &&
|
||||
/P2/.test(modal.textContent) && !li.querySelector(".is-task-drop"), [names, modal && modal.textContent]);
|
||||
modal.querySelector('input[value="22"]').checked = true;
|
||||
modal.querySelector("[data-move-ok]").click(); await settle(); await settle();
|
||||
check("[프로젝트 이동] [이동] → move-project(프로젝트·고른 섹션) 후 창 닫힘",
|
||||
moves.length === 1 && moves[0].project_id === 2 && moves[0].stage_id === 22 && !d.body.querySelector(".pj-move-modal"), moves);
|
||||
// 같은 프로젝트에 놓으면 창 없이 안내
|
||||
fire(card, "dragstart");
|
||||
fire(d.querySelector('.pj-side .pj-tree-li[data-id="1"]'), "drop"); await settle();
|
||||
check("[프로젝트 이동] 같은 프로젝트에 놓으면 창 없음", !d.body.querySelector(".pj-move-modal"));
|
||||
}
|
||||
// ── 세부 업무를 만들 때 협업자 같이(업무 창 추가 칸·보드 카드 새 줄) · 카드 기존 줄 협업자 · 대시보드 프로젝트별(2026-10-13) ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const posts = [], folPosts = [];
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () {
|
||||
return { body: { task: detail(101, "작업 A", { subtasks: [{ id: 911, title: "카드 세부", project_id: 1, parent_task_id: 101, followers: [] }] }) } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/projects\/1\/tasks$/, function (u, b) {
|
||||
posts.push(b); return { body: { task: detail(960 + posts.length, b.title, { parent_task_id: b.parent_task_id }) } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/tasks\/911\/followers$/, function (u, b) { folPosts.push(b); return { body: { followers: [b.email] } }; });
|
||||
const P = await boot(env); const d = env.d, w = env.w;
|
||||
const pickMe = async function () {
|
||||
const b = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (x) { return /me/i.test(x.textContent); });
|
||||
if (b) b.click();
|
||||
await settle();
|
||||
await wait(10); d.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
return !!b;
|
||||
};
|
||||
// 업무 창 추가 칸
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const addFol = d.getElementById("pj-subtask-add-followers");
|
||||
check("[세부 추가 협업자] 업무 창 추가 칸에 협업자 버튼(담당자 오른쪽)", !!addFol && /협업자 없음/.test(addFol.textContent));
|
||||
addFol.click(); await settle();
|
||||
check("[세부 추가 협업자] 멤버 메뉴에서 고름", await pickMe());
|
||||
check("[세부 추가 협업자] 버튼에 협업자 1명", /협업자 1명/.test(addFol.textContent), addFol.textContent);
|
||||
d.getElementById("pj-subtask-input").value = "새 세부";
|
||||
d.getElementById("pj-subtask-add").click(); await settle(); await settle();
|
||||
check("[세부 추가 협업자] [추가] 요청에 followers, 끝나면 칸 비움",
|
||||
posts.length === 1 && JSON.stringify(posts[0].followers) === '["me@test.local"]' && /협업자 없음/.test(addFol.textContent), [posts, addFol.textContent]);
|
||||
d.querySelector("#pj-modal-task [data-close]") && d.querySelector("#pj-modal-task [data-close]").click();
|
||||
await wait(400); await settle();
|
||||
// 보드 카드 — 기존 세부 업무 줄 협업자 + 새 줄 협업자
|
||||
d.querySelector('.pj-tab[data-view="board"]').click(); await settle();
|
||||
d.querySelector('.pj-card[data-task-id="101"] .pj-card-subtoggle').click(); await settle(); await settle();
|
||||
const cardFol = d.querySelector('.pj-card[data-task-id="101"] .pj-card-sub[data-sub-id="911"] .pj-card-sub-fol');
|
||||
check("[카드 세부 협업자] 기존 줄 담당자 오른쪽 협업자 아이콘", !!cardFol && cardFol.classList.contains("is-empty"));
|
||||
cardFol.click(); await settle(); await pickMe();
|
||||
check("[카드 세부 협업자] 고르면 POST·아이콘 갱신", folPosts.length === 1 && folPosts[0].email === "me@test.local" && !cardFol.classList.contains("is-empty"), folPosts);
|
||||
d.querySelector('.pj-card[data-task-id="101"] .pj-card-subadd').click(); await settle();
|
||||
const nf = d.querySelector('.pj-card[data-task-id="101"] .pj-card-subnew-fol');
|
||||
check("[카드 새 세부 협업자] 새 줄에 협업자 아이콘", !!nf);
|
||||
nf.click(); await settle(); await pickMe();
|
||||
const ni = d.querySelector('.pj-card[data-task-id="101"] .pj-card-subnew-title');
|
||||
ni.value = "카드 새 세부"; ni.dispatchEvent(new w.Event("input", { bubbles: true }));
|
||||
ni.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", bubbles: true })); await settle(); await settle();
|
||||
const last = posts[posts.length - 1];
|
||||
check("[카드 새 세부 협업자] Enter → 요청에 followers", posts.length === 2 && last.title === "카드 새 세부" &&
|
||||
JSON.stringify(last.followers) === '["me@test.local"]', posts);
|
||||
// 대시보드 — 업무 합계(프로젝트별) 카드, 완료 상태별 카드 바로 왼쪽
|
||||
P.state().tasks.forEach(function (t) { if (t.id === 101) t.completed_at = "2026-09-29T10:00:00+09:00"; });
|
||||
d.querySelector('.pj-tab[data-view="dashboard"]').click(); await settle();
|
||||
const titles = Array.from(d.querySelectorAll("#pj-dash .pj-dash-card-title")).map(function (n) { return n.textContent; });
|
||||
const pi = titles.indexOf("업무 합계(프로젝트별)");
|
||||
check("[대시보드 프로젝트별] 카드가 완료 상태별 바로 왼쪽", pi >= 0 && titles[pi + 1] === "업무 합계(완료 상태별)", titles);
|
||||
const prow = Array.from(d.querySelectorAll("#pj-dash .pj-dash-projrow")).map(function (r) {
|
||||
return r.querySelector(".pj-dash-projname").textContent + "|" + r.querySelector(".pj-dash-projval").textContent;
|
||||
});
|
||||
check("[대시보드 프로젝트별] 프로젝트마다 완료/전체·%", prow.length >= 1 && /\|1\/2 · 50%$/.test(prow[0]), prow);
|
||||
}
|
||||
// ── 나를 태그·작업 배정 알림 팝업 — 본 것 이후 새 알림만, 깜박이는 팝업, 닫기 전까지 유지 ──
|
||||
{
|
||||
@@ -786,6 +1017,11 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-side-allview").click(); await settle();
|
||||
// 전체 보기의 기본 보기는 대시보드(2026-10-13) — 확인 뒤 보드로 바꿔 카드를 센다.
|
||||
const activeTab = d.querySelector("#pj-view-tabs .pj-tab.is-active");
|
||||
check("[전체 보기] 기본 보기 = 대시보드", activeTab && activeTab.dataset.view === "dashboard" &&
|
||||
!d.querySelector('.pj-view[data-view="dashboard"]').hidden, activeTab && activeTab.dataset.view);
|
||||
d.querySelector('#pj-view-tabs .pj-tab[data-view="board"]').click(); await settle();
|
||||
const cards = function (id) { return d.querySelectorAll('.pj-card[data-task-id="' + id + '"]').length; };
|
||||
check("[전체 보기] 연결된 작업(원 소속 못 봄)도 한 장, 원 소속 작업은 그대로 한 장", cards(301) === 1 && cards(101) === 1 && cards(103) === 1,
|
||||
[cards(301), cards(101), cards(103)]);
|
||||
|
||||
@@ -19,7 +19,7 @@ sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.project import store # noqa: E402
|
||||
from app.modules.project.router import _goal_area_layout, _goal_label_spans # noqa: E402
|
||||
from app.modules.project.router import _goal_area_layout, _goal_label_spans, _meeting_label_spans # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_after_logout %}{% endblock %}{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
@@ -151,6 +151,22 @@ def meeting_merged_ctx() -> dict:
|
||||
return ctx
|
||||
|
||||
|
||||
def meeting_groups_ctx(added: bool = False) -> dict:
|
||||
"""항목 칸 묶음(027) — 상품 구역: 상품1(묶음 첫 줄) + 이어 붙은 줄(id 3, label_cont) — 실제 라우터 도우미로 칸 계산.
|
||||
added = 상품1 아래에 같은 항목 칸으로 줄(id 9)을 추가한 뒤의 화면(다시 받기 응답)."""
|
||||
ctx = meeting_ctx(True, False, can_sync=False)
|
||||
rows = ctx["meeting"]["sections"][0]["rows"]
|
||||
rows[1].update(label="", label_cont=True)
|
||||
if added:
|
||||
new = copy.deepcopy(rows[1])
|
||||
new.update(id=9, content="", target_amount=None, prev=None)
|
||||
rows.insert(1, new)
|
||||
ctx["meeting"]["items"].insert(1, new)
|
||||
for sec in ctx["meeting"]["sections"]:
|
||||
_meeting_label_spans(sec["rows"])
|
||||
return ctx
|
||||
|
||||
|
||||
def main() -> None:
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
@@ -171,6 +187,8 @@ def main() -> None:
|
||||
"meeting_layout_admin.html": ("project/goal_meeting.html", meeting_layout_ctx(True)),
|
||||
"meeting_layout_ro.html": ("project/goal_meeting.html", meeting_layout_ctx(False)),
|
||||
"meeting_merged.html": ("project/goal_meeting.html", meeting_merged_ctx()),
|
||||
"meeting_groups.html": ("project/goal_meeting.html", meeting_groups_ctx()),
|
||||
"meeting_groups_added.html": ("project/goal_meeting.html", meeting_groups_ctx(added=True)),
|
||||
"meeting_content_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False, can_sync=False) | {"meeting_embedded": True}),
|
||||
"meeting_content_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False) | {"meeting_embedded": True}),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""실적 대시보드(index.html)·광고비(ads.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_ads.html · perf_settings.html
|
||||
|
||||
화면 데이터는 실제 build_dashboard·build_settings 로 만든다(저장소만 가짜). DB·쇼핑몰 API 는 쓰지 않는다.
|
||||
쿠팡은 수동 입력 켬(10/5 수동 값 87,000, 10/6 은 API 값만), 카카오도 켬(값 없음), 나머지는 끔.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
|
||||
from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
|
||||
"{% block scripts %}{% endblock %}</body>")
|
||||
ORDER = ["cafe24", "naver", "coupang", "toss", "gsshop", "elevenst", "ohouse", "gmarket", "kakao", "lotteon"]
|
||||
NAMES = {"cafe24": "카페24", "naver": "네이버 스마트스토어", "coupang": "쿠팡", "toss": "토스쇼핑", "gsshop": "GS샵",
|
||||
"elevenst": "11번가", "ohouse": "오늘의집", "gmarket": "G마켓", "kakao": "카카오", "lotteon": "롯데ON"}
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def list_marketplaces(self):
|
||||
return [{"code": c, "name": NAMES[c], "enabled": True, "include_in_sales": True, "sort_order": i * 10,
|
||||
"manual_input": c in ("coupang", "kakao")} for i, c in enumerate(ORDER, 1)]
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
api = {(date(2026, 10, 5), "coupang"): 50000, (date(2026, 10, 6), "coupang"): 7000,
|
||||
(date(2026, 10, 5), "cafe24"): 100000}
|
||||
out = {k: v for k, v in api.items() if start <= k[0] <= end and k[1] in codes}
|
||||
out.update(self.manual_amounts(start, end, codes))
|
||||
return out
|
||||
|
||||
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||
manual = {(date(2026, 10, 5), "coupang"): 87000}
|
||||
return {k: v for k, v in manual.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
def rate_table(self):
|
||||
return {"coupang": [(date(2026, 1, 1), Decimal("12"))]}
|
||||
|
||||
def statuses(self):
|
||||
return {}
|
||||
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual"),
|
||||
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")}
|
||||
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
|
||||
|
||||
def ad_roas(self, start, end):
|
||||
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5")}
|
||||
return {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
|
||||
|
||||
def env() -> jinja2.Environment:
|
||||
e = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "performance", "templates")),
|
||||
]), autoescape=True)
|
||||
return e
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
e = env()
|
||||
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": ""}
|
||||
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24", "coupang"])
|
||||
html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx)
|
||||
with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0)
|
||||
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -53,6 +53,29 @@ def main() -> None:
|
||||
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
|
||||
render_one(env, name, admin)
|
||||
render_inbox(env)
|
||||
render_mytasks(env)
|
||||
|
||||
|
||||
def render_mytasks(env) -> None:
|
||||
"""내 업무(project/mytasks.html) — 내 업무 101·102, 남의 상위 업무 아래 내 세부 업무 501."""
|
||||
def t(tid: int, title: str, **kw) -> dict:
|
||||
base = {"id": tid, "title": title, "project_id": 1, "project_name": "P1", "project_color": "#4573d2",
|
||||
"stage_name": "할 일", "assignee_email": ME, "priority": "normal", "due_date": None, "start_date": None,
|
||||
"completed_at": None, "comment_count": 0, "subtask_total": 0, "subtask_done": 0, "parent_task_id": None}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
html = env.get_template("project/mytasks.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, pj_pro=False, pj_admin=False,
|
||||
nav_projects=PROJECTS, goal_years=[2026], my_open_total=3, mention_unread=0,
|
||||
color_palette=["#4573d2"], project_icons=["folder"], project_asana_icons=[],
|
||||
my_tasks=[t(101, "작업 A"), t(102, "작업 B"),
|
||||
t(501, "내 세부", parent_task_id=300, parent_title="남의 상위", parent_assignee_email="bob@test.local")],
|
||||
avatars={}, priority_labels={"low": "낮음", "normal": "보통", "high": "높음"}, today="2026-10-13",
|
||||
)
|
||||
path = os.path.join(OUT_DIR, "mytasks_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
def render_inbox(env) -> None:
|
||||
|
||||
@@ -167,3 +167,14 @@ def test_box_list_workbook_weight_column():
|
||||
assert ws.cell(row=6, column=5).value is None
|
||||
ws2 = build_box_list_workbook({"ship_date": "2026-10-02"}, _boxes()).active # 예전처럼 4열
|
||||
assert ws2.cell(row=2, column=5).value is None and ws2.cell(row=2, column=4).value == "수량"
|
||||
|
||||
|
||||
def test_g_to_kg_rounds_half_up_to_one_decimal():
|
||||
"""출고 상세 상자 목록 무게(kg) — 소수 둘째 자리에서 반올림해 첫째 자리까지."""
|
||||
from app.modules.cupang.router import _g_to_kg
|
||||
|
||||
assert _g_to_kg(3000) == "3.0"
|
||||
assert _g_to_kg(1250) == "1.3" # 1.25 → 1.3 (사사오입)
|
||||
assert _g_to_kg(1249) == "1.2"
|
||||
assert _g_to_kg(1234567) == "1,234.6"
|
||||
assert _g_to_kg(None) is None
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user