Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -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
|
||||
@@ -146,6 +148,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 +212,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 +225,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=20261012a" />{% 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=20261012a" />{% 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=20261012a" />{% 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=20261012a" />{% 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=20261012a" />{% 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=20261012a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||
@@ -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,25 @@
|
||||
<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">합계</td>
|
||||
<td></td>
|
||||
<td></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=20261012i" />
|
||||
<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=20261012l" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -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,42 @@ 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
|
||||
PROBE_MAX_DAYS = 31
|
||||
KST_OFFSET = timedelta(hours=9)
|
||||
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||
|
||||
|
||||
def signed_date(now: float | None = None) -> str:
|
||||
@@ -54,14 +88,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 = "쿠팡"
|
||||
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 +254,206 @@ 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.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 >= 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 가."""
|
||||
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||
for st in STATUSES:
|
||||
rows = self._pages(ctx, path, {"createdAtFrom": f"{a.isoformat()}+09:00",
|
||||
"createdAtTo": f"{b.isoformat()}+09:00",
|
||||
"status": st, "maxPerPage": PAGE_SIZE})
|
||||
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 = self._pages(ctx, path, {"paidDateFrom": a.strftime("%Y%m%d"), "paidDateTo": b.strftime("%Y%m%d")}, rg=True)
|
||||
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(출고된 주문만). 배송비 제외"}
|
||||
|
||||
@@ -19,16 +19,17 @@ from .ohouse import OhouseAdapter
|
||||
from .toss import TossAdapter
|
||||
|
||||
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 002)
|
||||
Cafe24Adapter(),
|
||||
NaverAdapter(),
|
||||
CoupangAdapter(),
|
||||
TossAdapter(),
|
||||
GsshopAdapter(),
|
||||
ElevenstAdapter(),
|
||||
OhouseAdapter(),
|
||||
GmarketAdapter(),
|
||||
KakaoAdapter(),
|
||||
GsshopAdapter(),
|
||||
ElevenstAdapter(),
|
||||
LotteonAdapter(),
|
||||
TossAdapter(),
|
||||
)
|
||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||
|
||||
|
||||
@@ -58,6 +58,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 +148,8 @@ 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,
|
||||
"last_update_at": store.last_update_at(),
|
||||
"running": store.running_codes(),
|
||||
"no_marketplaces": not all_codes,
|
||||
@@ -175,7 +182,7 @@ 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,
|
||||
|
||||
@@ -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,56 @@ 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 daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
|
||||
@@ -10,8 +10,9 @@ 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} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||
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 입력칸 + 저장 여부(비밀 원문 없음)
|
||||
@@ -44,6 +45,9 @@ MAX_EVENT_DAYS = 31
|
||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
|
||||
|
||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||
@@ -270,6 +274,39 @@ 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})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -277,11 +314,17 @@ 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
|
||||
|
||||
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})
|
||||
|
||||
|
||||
|
||||
@@ -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=20261012c" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -118,7 +118,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 +130,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 +146,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>
|
||||
|
||||
<!-- ── 그래프 ── -->
|
||||
@@ -239,4 +250,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012b" 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=20261012c" />{% 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="수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신)">
|
||||
<input type="checkbox" data-field="manual_input"{% if r.manual_input %} checked{% 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>
|
||||
@@ -136,13 +143,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="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 +201,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012b" defer></script>{% endblock %}
|
||||
|
||||
@@ -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():
|
||||
@@ -1729,3 +1883,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
|
||||
|
||||
+327
-7
@@ -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
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 프로젝트 / 서브프로젝트
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -2771,7 +2776,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 +3015,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 +3023,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 +3060,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 +3132,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 +3170,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 +3350,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 +3376,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:
|
||||
|
||||
@@ -1465,6 +1465,16 @@ 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:
|
||||
@@ -1525,7 +1535,7 @@ 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 = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
|
||||
@@ -2914,6 +2924,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 +2970,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:
|
||||
@@ -3426,6 +3456,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
|
||||
@@ -3669,7 +3700,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 +3713,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 +3770,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})
|
||||
|
||||
@@ -431,6 +431,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 뒤에만 된다."""
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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=20261012i" />
|
||||
<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=20261012l" 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=20261012i" />
|
||||
<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=20261012l" 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=20261012i" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -636,9 +636,11 @@
|
||||
<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>맨 오른쪽 <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">
|
||||
@@ -697,6 +699,8 @@
|
||||
<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>
|
||||
|
||||
|
||||
@@ -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=20261012i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -101,5 +101,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=20261012l" 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=20261012i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261012l" 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=20261012i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261012l" 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=20261012i" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -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>
|
||||
@@ -488,5 +468,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=20261012l" 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=20261012i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261012l" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1362,6 +1362,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); }
|
||||
|
||||
@@ -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();
|
||||
})();
|
||||
@@ -102,11 +102,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 +129,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; }
|
||||
|
||||
@@ -333,6 +333,89 @@
|
||||
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", "/performance/api/manual-sales/" + 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.title = manual !== "" ? "수동 입력값 — 눌러 고치기(비우고 저장하면 API 값)" : "눌러 총매출 직접 입력";
|
||||
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 + " 총매출" });
|
||||
input.value = digitsOf(td);
|
||||
const g = td.querySelector(".v-gross");
|
||||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || "총매출";
|
||||
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) + " 주문 내역";
|
||||
@@ -987,7 +1070,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,7 +1080,8 @@
|
||||
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;
|
||||
@@ -1038,7 +1122,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 };
|
||||
})();
|
||||
|
||||
+38
-7
@@ -2475,6 +2475,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 +2552,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 +2578,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 +2820,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 +3063,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; }
|
||||
|
||||
+620
-127
@@ -7511,14 +7511,23 @@
|
||||
|
||||
// ── 설명(contenteditable) — 붙여넣기/업로드로 이미지를 끼워 넣는다 ──
|
||||
function initDescEditor() {
|
||||
const box = el("pj-t-desc");
|
||||
return createDescEditor({
|
||||
box: el("pj-t-desc"), fmtbar: el("pj-desc-fmtbar"), imgInput: el("pj-desc-img-input"),
|
||||
hint: el("pj-desc-hint"), mentions: true,
|
||||
});
|
||||
}
|
||||
// 설명 편집기 본체 — 작업 창(initDescEditor)과 긴급 공지 관리 화면(window.PJLib)이 같이 쓴다.
|
||||
// cfg.box·fmtbar·imgInput·hint — 요소, cfg.mentions — @태그(작업 설명란만),
|
||||
// cfg.uploadImage(file) → Promise<이미지 주소> — 주면 그걸로 올린다(없으면 작업 첨부로, setTaskId 필요).
|
||||
function createDescEditor(cfg) {
|
||||
const box = cfg.box;
|
||||
if (!box) return null;
|
||||
// @ 를 누르면 멤버 목록 → 고르면 멘션 칩이 들어간다(수신함에 쌓인다).
|
||||
attachMentionEditor(box);
|
||||
if (cfg.mentions) attachMentionEditor(box);
|
||||
const wrap = box.parentElement;
|
||||
const imgInput = el("pj-desc-img-input");
|
||||
const hint = el("pj-desc-hint");
|
||||
let taskId = null;
|
||||
const imgInput = cfg.imgInput || null;
|
||||
const hint = cfg.hint || null;
|
||||
let taskId = cfg.uploadImage ? "custom" : null; // 자체 업로드면 늘 이미지 추가 가능
|
||||
|
||||
// ── 서식 도구 모음(간단 워드프로세서) — execCommand 는 구식 API지만
|
||||
// 크롬/엣지는 여전히 지원하고, 이미 같은 파일의 이미지 삽입에서도 쓰고
|
||||
@@ -7608,7 +7617,7 @@
|
||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
|
||||
const fmtbar = el("pj-desc-fmtbar");
|
||||
const fmtbar = cfg.fmtbar || null;
|
||||
if (fmtbar) {
|
||||
fmtbar.addEventListener("mousedown", function (e) { e.preventDefault(); });
|
||||
fmtbar.addEventListener("click", function (e) {
|
||||
@@ -7964,16 +7973,18 @@
|
||||
saveSelection();
|
||||
const insertAt = lastRange ? lastRange.cloneRange() : null;
|
||||
beginUpload();
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
naturalImageSize(file),
|
||||
fetch("/project/api/tasks/" + myTaskId + "/attachments", { method: "POST", body: fd }),
|
||||
]);
|
||||
const dims = results[0], res = results[1];
|
||||
// 작업 설명란 = 그 작업 첨부로 올린다. 다른 화면(긴급 공지)은 cfg.uploadImage 가 주소를 돌려준다.
|
||||
const upload = cfg.uploadImage || async function (f) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", f);
|
||||
const res = await fetch("/project/api/tasks/" + myTaskId + "/attachments", { method: "POST", body: fd });
|
||||
if (!res.ok) { let m = res.statusText; try { m = (await res.json()).detail; } catch (_) {} throw new Error(m); }
|
||||
const data = await res.json();
|
||||
return "/project/api/attachments/" + data.attachment.id + "/inline";
|
||||
};
|
||||
try {
|
||||
const results = await Promise.all([naturalImageSize(file), upload(file)]);
|
||||
const dims = results[0], imgSrc = results[1];
|
||||
if (myGen !== editorGen || myTaskId !== taskId) {
|
||||
showToast("이미지는 원래 작업의 첨부 파일로 저장됐습니다(작업 창이 바뀌어 설명에는 넣지 않았습니다).");
|
||||
return;
|
||||
@@ -7985,7 +7996,7 @@
|
||||
if (insertAt) {
|
||||
try { const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(insertAt); } catch (_) {}
|
||||
}
|
||||
insertHtmlAtCursor('<img src="/project/api/attachments/' + data.attachment.id + '/inline" alt=""' + widthAttr + '>');
|
||||
insertHtmlAtCursor('<img src="' + escapeHtml(imgSrc) + '" alt=""' + widthAttr + '>');
|
||||
} catch (e) { alert("이미지 업로드 실패: " + e.message); }
|
||||
finally { endUpload(); }
|
||||
}
|
||||
@@ -9092,15 +9103,20 @@
|
||||
tipEl.textContent = text;
|
||||
tipEl.hidden = false;
|
||||
// 화면 가장자리 보정 — 좌우로 넘치면 말풍선만 안쪽으로 밀고 꼬리는
|
||||
// 커서를 계속 가리키게(--pj-tip-shift). 위가 모자라면 커서 아래로 뒤집는다.
|
||||
// 커서를 계속 가리키게(--pj-tip-shift).
|
||||
// 늘 커서 **위**에 — 마우스 화살표(핫스팟에서 아래로 약 20px)에 가려지지 않게. 화면 맨 위(회의록 머리 버튼 등)라
|
||||
// 여유가 적으면 꼬리 간격을 줄여서라도 위에(말풍선 아래 끝 = 커서 8px 위), 그래도 안 들어갈 때만 아래로 뒤집되
|
||||
// 화살표 길이만큼 띄운다(예전엔 위 여백 20px 미만이면 커서 바로 아래 22px — 화살표가 글자를 가렸다).
|
||||
const w = tipEl.offsetWidth, h = tipEl.offsetHeight;
|
||||
const vw = document.documentElement.clientWidth;
|
||||
const cx = Math.min(Math.max(x, 8 + w / 2), vw - 8 - w / 2);
|
||||
const below = y - 16 - h < 4;
|
||||
// CSS 기본 위치: 말풍선 아래 끝 = top − 6px(transform). top = y−10 → 커서 16px 위, top = y−2 → 커서 8px 위.
|
||||
const roomy = y - 16 - h >= 2;
|
||||
const below = !roomy && y - 8 - h < 0;
|
||||
tipEl.classList.toggle("is-below", below);
|
||||
tipEl.style.setProperty("--pj-tip-shift", (x - cx) + "px");
|
||||
tipEl.style.left = cx + "px";
|
||||
tipEl.style.top = (below ? y + 22 : y - 10) + "px";
|
||||
tipEl.style.top = (below ? y + 28 : roomy ? y - 10 : y - 2) + "px";
|
||||
}
|
||||
function hide() { shown = false; if (tipEl) tipEl.hidden = true; }
|
||||
document.addEventListener("mouseover", function (e) {
|
||||
@@ -10556,6 +10572,7 @@
|
||||
btn.setAttribute("aria-pressed", prevFirst ? "true" : "false");
|
||||
}
|
||||
arrange();
|
||||
table.addEventListener("pj-meet-rows", arrange); // 줄 구조를 다시 끼운 뒤(refreshMeeting) 새 줄도 같은 순서로
|
||||
btn.addEventListener("click", function () {
|
||||
prevFirst = !prevFirst;
|
||||
try { localStorage.setItem(KEY, prevFirst ? "prev" : "this"); } catch (_) {}
|
||||
@@ -10643,17 +10660,28 @@
|
||||
});
|
||||
}
|
||||
|
||||
// ── 회의록 머리 ③ 작업 등록 표 — 제목 입력, 담당자·프로젝트·섹션 칸을 누르면 목록(showContextMenu — body 에 붙음),
|
||||
// [적용] = 그 프로젝트에 작업 만들기(POST /project/api/projects/{id}/tasks, 담당자는 그 프로젝트 멤버·소유자만 —
|
||||
// 서버 _check_assignee). 프로젝트 목록은 내가 멤버인 최상위 프로젝트(GET /project/api/projects).
|
||||
// 줄은 이 브라우저에 보관(localStorage pj_meet_quick:{이메일}) — 새로고침해도 남는다(등록된 줄도 — 나중에 삭제할 수 있게).
|
||||
// 등록된 줄의 [삭제] = 확인 뒤 그 작업을 프로젝트에서도 삭제(DELETE /project/api/tasks/{id}, 휴지통 3개월), 적용 전 줄의 × = 줄만 지움.
|
||||
// ── 회의록 머리 ③ 작업 등록 표(2026-10-12) — 주차마다 한 표를 서버에(project_db 025, 모두가 같은 표).
|
||||
// 예전엔 각자 브라우저(localStorage)에만 있어 다른 사람이 적거나 등록한 줄이 보이지 않았다.
|
||||
// · 제목 입력, 담당자·프로젝트·섹션 칸을 누르면 목록(showContextMenu — body 에 붙음). 프로젝트는 내가 멤버인 최상위(완료 제외).
|
||||
// · 빈 줄 3개는 화면에만 — 칸을 처음 채우는 순간 서버에 줄이 생긴다(POST), 그 뒤는 칸마다 저장(PUT, 줄마다 차례대로).
|
||||
// · [적용] = 서버가 줄을 잠그고 그 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림, 두 사람이 눌러도 하나).
|
||||
// · 등록된 줄의 [삭제] = 확인 뒤 그 작업도 삭제(휴지통 3개월), 적용 전 줄의 × = 줄만 지움.
|
||||
// · 30초마다·창을 다시 볼 때 다시 읽는다(입력 중·저장 중엔 건너뜀). 회의 완료면 읽기 전용.
|
||||
// · 이 브라우저에 남은 예전 표(pj_meet_quick:…)는 처음 열 때 서버로 한 번 옮기고 지운다.
|
||||
// · 작업 칸(026 parent_task_id) — 비우면 그 섹션에 새 작업, 이미 있는 작업을 고르면 [적용] 때 그 작업의 세부 작업으로(섹션 없음).
|
||||
// · 등록된 줄의 제목을 누르면 오른쪽에 작업 창(편집, 수신함과 같은 iframe·저장 대기).
|
||||
// · [크게 열기] — 같은 표를 넓은 창으로 옮겨 쓴다(줄·저장 그대로), 닫으면 제자리.
|
||||
function initMeetQuickTasks() {
|
||||
const box = el("pj-meet-quick");
|
||||
if (!box) return;
|
||||
const tbody = box.querySelector("tbody");
|
||||
const week = box.dataset.week || "";
|
||||
const locked = box.dataset.locked === "1";
|
||||
const listUrl = "/project/api/goals/meetings/" + week + "/quick-tasks";
|
||||
const rowUrl = function (id) { return "/project/api/goals/meeting-quick-tasks/" + id; };
|
||||
const wrap = document.querySelector(".pj-wrap");
|
||||
const KEY = "pj_meet_quick:" + ((wrap && wrap.dataset.me) || "");
|
||||
const LEGACY_KEY = "pj_meet_quick:" + ((wrap && wrap.dataset.me) || "");
|
||||
const LOCAL_KEY = LEGACY_KEY + ":" + week;
|
||||
const people = {}, faces = {};
|
||||
(window.PJ_MEET_MEMBERS || []).forEach(function (m) {
|
||||
people[String(m.email).toLowerCase()] = m.name;
|
||||
@@ -10666,19 +10694,31 @@
|
||||
return url ? '<img class="pj-avatar pj-meet-quick-face" src="' + escapeHtml(url) + '" alt="" referrerpolicy="no-referrer">'
|
||||
: '<span class="pj-meet-quick-face is-ini">' + escapeHtml(nameOf(email).slice(0, 1)) + "</span>";
|
||||
};
|
||||
const blank = function () { return { title: "", assignee: "", projectId: null, projectName: "", stageId: null, stageName: "" }; };
|
||||
let rows = [];
|
||||
try { rows = (JSON.parse(localStorage.getItem(KEY) || "[]") || []).filter(function (r) { return r && typeof r === "object"; }); } catch (_) { rows = []; }
|
||||
while (rows.length < 3) rows.push(blank());
|
||||
const save = function () {
|
||||
try { localStorage.setItem(KEY, JSON.stringify(rows.filter(function (r) { return r.done || r.title || r.projectId || r.assignee; }))); } catch (_) {}
|
||||
const blank = function () {
|
||||
return { id: null, title: "", assignee: "", projectId: null, projectName: "", stageId: null, stageName: "",
|
||||
parentTaskId: null, parentTaskTitle: "", taskId: null, registered: false, visible: true, taskExists: true, chain: null };
|
||||
};
|
||||
function fromServer(t) {
|
||||
return { id: t.id, title: t.title || "", assignee: t.assignee_email || "", projectId: t.project_id,
|
||||
projectName: t.project_name || "", stageId: t.stage_id, stageName: t.stage_name || "",
|
||||
parentTaskId: t.parent_task_id || null, parentTaskTitle: t.parent_task_title || "", taskId: t.task_id,
|
||||
registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null };
|
||||
}
|
||||
let rows = [];
|
||||
let ready = false, unavailable = "";
|
||||
function padBlank() {
|
||||
if (locked) return;
|
||||
const open = rows.filter(function (r) { return !r.registered; }).length;
|
||||
for (let i = open; i < 3; i++) rows.push(blank());
|
||||
}
|
||||
|
||||
let projects = null;
|
||||
const memberCache = {}, stageCache = {};
|
||||
const memberCache = {}, stageCache = {}, taskCache = {};
|
||||
async function loadProjects() {
|
||||
if (projects) return projects;
|
||||
const res = await api("GET", "/project/api/projects");
|
||||
projects = (res.projects || []).filter(function (p) { return !p.parent_id; });
|
||||
// 완료 프로젝트는 고를 목록에서 뺀다(새 작업을 넣을 곳이 아니다) — 서버는 보관만 뺀다
|
||||
projects = (res.projects || []).filter(function (p) { return !p.parent_id && p.status !== "completed"; });
|
||||
return projects;
|
||||
}
|
||||
async function membersOf(pid) {
|
||||
@@ -10696,130 +10736,430 @@
|
||||
stageCache[pid] = (res.stages || []).slice().sort(function (a, b) { return a.sort_order - b.sort_order; });
|
||||
return stageCache[pid];
|
||||
}
|
||||
function cell(kind, text, placeholder) {
|
||||
return '<button type="button" class="pj-meet-pick-cell' + (text ? "" : " is-empty") + '" data-pick="' + kind + '">' +
|
||||
escapeHtml(text || placeholder) + "</button>";
|
||||
// 작업 칸 후보 — 그 프로젝트의 (그 섹션) 미완료 메인 작업. 고르면 [적용] 때 그 작업의 세부 작업으로 만든다.
|
||||
async function tasksOf(pid) {
|
||||
if (taskCache[pid]) return taskCache[pid];
|
||||
const res = await api("GET", "/project/api/projects/" + pid + "/tasks");
|
||||
taskCache[pid] = (res.tasks || []).filter(function (t) { return t.project_id === pid && !t.completed_at && !t.parent_task_id; });
|
||||
return taskCache[pid];
|
||||
}
|
||||
|
||||
// ── 저장 — 줄마다 차례대로. 서버에 없는 줄은 처음 채울 때 만든다(지금 칸 전부를 보낸다) ──
|
||||
let pendingSaves = 0;
|
||||
function persist(r, patch) {
|
||||
pendingSaves++;
|
||||
const run = async function () {
|
||||
if (!r.id) {
|
||||
const res = await api("POST", listUrl, {
|
||||
title: r.title, assignee_email: r.assignee, project_id: r.projectId, stage_id: r.stageId,
|
||||
parent_task_id: r.parentTaskId,
|
||||
});
|
||||
r.id = res.task.id;
|
||||
} else {
|
||||
await api("PUT", rowUrl(r.id), patch);
|
||||
}
|
||||
};
|
||||
r.chain = (r.chain || Promise.resolve()).then(run).catch(function (e) {
|
||||
showToast("작업 등록 표 저장 실패: " + e.message, "error");
|
||||
if (e.status === 409 || e.status === 400) setTimeout(function () { load(true); }, 0); // 서버 상태로 되돌림
|
||||
}).finally(function () { pendingSaves--; });
|
||||
return r.chain;
|
||||
}
|
||||
function cell(kind, text, placeholder, disabled, title) {
|
||||
return '<button type="button" class="pj-meet-pick-cell' + (text ? "" : " is-empty") + '" data-pick="' + kind + '"' +
|
||||
(title ? ' title="' + escapeHtml(title) + '"' : "") + (disabled ? " disabled" : "") + ">" + escapeHtml(text || placeholder) + "</button>";
|
||||
}
|
||||
function render() {
|
||||
if (unavailable) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="pj-meet-quick-note">' + escapeHtml(unavailable) + "</td></tr>";
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = rows.map(function (r, i) {
|
||||
return '<tr data-i="' + i + '"' + (r.done ? ' class="is-done"' : "") + ">" +
|
||||
'<td><input type="text" data-field="title" maxlength="200" placeholder="작업 제목" value="' + escapeHtml(r.title) + '"></td>' +
|
||||
const ro = locked || r.registered;
|
||||
let acts;
|
||||
if (r.registered) {
|
||||
// 체크 아이콘만(말풍선에 등록됨/작업 삭제됨) — 볼 수 있으면 새 탭 링크
|
||||
const label = !r.taskExists ? "작업 삭제됨" : "등록됨";
|
||||
const ic = '<span class="material-symbols-outlined">check_circle</span>';
|
||||
acts = (r.visible && r.taskId && r.taskExists
|
||||
? '<a class="pj-meet-quick-done" href="/project/t/' + r.taskId + '" target="_blank" rel="noopener" title="' + label + ' — 새 탭에서 열기" aria-label="' + label + '">' + ic + "</a>"
|
||||
: '<span class="pj-meet-quick-done' + (r.taskExists ? "" : " is-gone") + '" title="' + label + '" aria-label="' + label + '">' + ic + "</span>") +
|
||||
(!locked && r.visible
|
||||
? '<button type="button" class="pj-meet-quick-del" data-quick="delete" title="' +
|
||||
(r.taskExists ? "이 작업을 프로젝트에서도 삭제(휴지통에 3개월 보관)" : "이 줄 지우기") + '">' +
|
||||
'<span class="material-symbols-outlined">delete</span></button>' : "");
|
||||
} else if (locked) {
|
||||
acts = "";
|
||||
} else {
|
||||
acts = '<button type="button" class="pj-meet-quick-apply" data-quick="apply">적용</button>' +
|
||||
'<button type="button" class="pj-meet-quick-del" data-quick="remove" title="이 줄 지우기(아직 등록 전)">' +
|
||||
'<span class="material-symbols-outlined">close</span></button>';
|
||||
}
|
||||
// 제목 — 등록된 줄은 누르면 오른쪽에 작업 창(편집), 아니면 입력칸
|
||||
const titleCell = r.registered
|
||||
? (r.visible && r.taskId && r.taskExists
|
||||
? '<button type="button" class="pj-meet-quick-open" data-quick="open" title="오른쪽에 작업 창 열기(편집)">' + escapeHtml(r.title || "(제목 없음)") + "</button>"
|
||||
: '<span class="pj-meet-quick-open is-plain">' + escapeHtml(r.title || "(제목 없음)") + "</span>")
|
||||
: '<input type="text" data-field="title" maxlength="200" placeholder="' + (r.parentTaskId ? "세부 작업 제목" : "작업 제목") + '" value="' +
|
||||
escapeHtml(r.title) + '"' + (ro ? " readonly" : "") + ">";
|
||||
// 작업 칸 — 비우면 그 섹션에 새 작업, 고르면 그 작업의 세부 작업(↳ 표시)
|
||||
const taskCell = r.parentTaskId
|
||||
? cell("task", "↳ " + (r.parentTaskTitle || "작업"), "", ro, "이 작업의 세부 작업으로 등록")
|
||||
: cell("task", "", r.registered ? "—" : "새 작업", ro || !r.projectId, r.projectId ? "고르면 그 작업의 세부 작업으로 등록(비우면 섹션에 새 작업)" : "프로젝트를 먼저 고르세요");
|
||||
return '<tr data-i="' + i + '"' + (r.registered ? ' class="is-done"' : "") + ">" +
|
||||
'<td class="pj-meet-quick-title">' + titleCell + "</td>" +
|
||||
"<td>" + (r.assignee
|
||||
? '<button type="button" class="pj-meet-pick-cell is-person" data-pick="assignee">' + faceHtml(r.assignee) +
|
||||
"<span>" + escapeHtml(nameOf(r.assignee)) + "</span></button>"
|
||||
: cell("assignee", "", "담당자")) + "</td>" +
|
||||
"<td>" + cell("project", r.projectName, "프로젝트") + "</td>" +
|
||||
"<td>" + cell("stage", r.stageName, "섹션") + "</td>" +
|
||||
'<td class="pj-meet-quick-acts">' + (r.done
|
||||
? '<span class="pj-meet-quick-done"><span class="material-symbols-outlined" style="font-size:16px">check_circle</span>' +
|
||||
'<a href="/project/p/' + r.done.pid + "?task=" + r.done.id + '" target="_blank" rel="noopener">등록됨</a></span>' +
|
||||
'<button type="button" class="pj-meet-quick-del" data-quick="delete" title="이 작업을 프로젝트에서도 삭제(휴지통에 3개월 보관)">' +
|
||||
'<span class="material-symbols-outlined">delete</span></button>'
|
||||
: '<button type="button" class="pj-meet-quick-apply" data-quick="apply">적용</button>' +
|
||||
'<button type="button" class="pj-meet-quick-del" data-quick="remove" title="이 줄 지우기(아직 등록 전)">' +
|
||||
'<span class="material-symbols-outlined">close</span></button>') + "</td></tr>";
|
||||
? '<button type="button" class="pj-meet-pick-cell is-person" data-pick="assignee"' + (ro ? " disabled" : "") + ">" +
|
||||
faceHtml(r.assignee) + "<span>" + escapeHtml(nameOf(r.assignee)) + "</span></button>"
|
||||
: cell("assignee", "", "담당자", ro)) + "</td>" +
|
||||
"<td>" + cell("project", r.projectName, "프로젝트", ro) + "</td>" +
|
||||
"<td>" + (r.parentTaskId ? '<span class="pj-meet-quick-inherit" title="세부 작업은 섹션이 없습니다(상위 작업을 따름)">—</span>'
|
||||
: cell("stage", r.stageName, "섹션", ro)) + "</td>" +
|
||||
"<td>" + taskCell + "</td>" +
|
||||
'<td class="pj-meet-quick-acts"><div class="pj-meet-quick-actbox">' + acts + "</div></td></tr>";
|
||||
}).join("");
|
||||
}
|
||||
function menuAt(btn, items) {
|
||||
const r = btn.getBoundingClientRect();
|
||||
showContextMenu(r.left, r.bottom + 2, items.length ? items : [{ label: "고를 항목이 없습니다", onClick: function () {} }]);
|
||||
}
|
||||
async function chooseProject(r, p) {
|
||||
if (r.projectId !== p.id) { r.stageId = null; r.stageName = ""; r.parentTaskId = null; r.parentTaskTitle = ""; }
|
||||
r.projectId = p.id; r.projectName = p.name;
|
||||
try {
|
||||
const [mem, stages] = await Promise.all([membersOf(p.id), stagesOf(p.id)]);
|
||||
if (r.assignee && mem.indexOf(r.assignee.toLowerCase()) < 0) {
|
||||
showToast(nameOf(r.assignee) + "님은 이 프로젝트 멤버가 아니어서 담당자를 비웠습니다.");
|
||||
r.assignee = "";
|
||||
}
|
||||
const open = stages.filter(function (st) { return !st.is_done_stage; }); // 완료 섹션은 자동으로 고르지 않는다
|
||||
if (!r.stageId && open.length) { r.stageId = open[0].id; r.stageName = open[0].name; }
|
||||
} catch (e) { showToast("프로젝트 정보를 읽지 못했습니다: " + e.message, "error"); }
|
||||
render();
|
||||
persist(r, { project_id: r.projectId, stage_id: r.stageId, assignee_email: r.assignee });
|
||||
}
|
||||
// 목록 맨 위 "+ 새 프로젝트" — 새 프로젝트는 Pro user 이상(서버 POST /api/projects 도 같은 기준), 만든 사람이 소유자.
|
||||
// 새 프로젝트는 섹션 없이 시작하므로 섹션 칸은 비워 둔다(섹션 칸 맨 위 "+ 새 섹션"으로 바로 만들 수 있다).
|
||||
async function addProject(r) {
|
||||
const name = await prompt("새 프로젝트 이름", "");
|
||||
if (name == null || !String(name).trim()) return;
|
||||
try {
|
||||
const res = await api("POST", "/project/api/projects", { name: String(name).trim() });
|
||||
const p = res.project;
|
||||
if (projects) projects.push(p);
|
||||
memberCache[p.id] = [String(p.owner_email || "").toLowerCase()].filter(Boolean);
|
||||
stageCache[p.id] = [];
|
||||
taskCache[p.id] = [];
|
||||
showToast("프로젝트 ‘" + p.name + "’를 만들었습니다.");
|
||||
await chooseProject(r, p);
|
||||
} catch (e) { showToast("프로젝트 만들기 실패: " + e.message, "error"); }
|
||||
}
|
||||
async function pickProject(r, btn) {
|
||||
const list = await loadProjects();
|
||||
menuAt(btn, list.map(function (p) {
|
||||
return { label: p.name, icon: menuIcon("folder"), checked: r.projectId === p.id, onClick: async function () {
|
||||
if (r.projectId !== p.id) { r.stageId = null; r.stageName = ""; }
|
||||
r.projectId = p.id; r.projectName = p.name;
|
||||
try {
|
||||
const [mem, stages] = await Promise.all([membersOf(p.id), stagesOf(p.id)]);
|
||||
if (r.assignee && mem.indexOf(r.assignee.toLowerCase()) < 0) {
|
||||
showToast(nameOf(r.assignee) + "님은 이 프로젝트 멤버가 아니어서 담당자를 비웠습니다.");
|
||||
r.assignee = "";
|
||||
}
|
||||
if (!r.stageId && stages.length) { r.stageId = stages[0].id; r.stageName = stages[0].name; }
|
||||
} catch (e) { showToast("프로젝트 정보를 읽지 못했습니다: " + e.message, "error"); }
|
||||
save(); render();
|
||||
} };
|
||||
}));
|
||||
const pro = el("pj-meet-pane") && el("pj-meet-pane").dataset.pro === "true";
|
||||
const head = pro ? [{ label: "새 프로젝트", icon: menuIcon("add"), onClick: function () { addProject(r); } }, null] : [];
|
||||
menuAt(btn, head.concat(list.map(function (p) {
|
||||
return { label: p.name, icon: menuIcon("folder"), checked: r.projectId === p.id, onClick: function () { chooseProject(r, p); } };
|
||||
})));
|
||||
}
|
||||
async function pickAssignee(r, btn) {
|
||||
// 프로젝트를 골랐으면 그 프로젝트 멤버·소유자만(작업을 볼 수 있는 사람), 아니면 프로젝트 권한이 있는 전체 직원
|
||||
const emails = r.projectId ? await membersOf(r.projectId)
|
||||
: (window.PJ_MEET_MEMBERS || []).map(function (m) { return String(m.email).toLowerCase(); });
|
||||
menuAt(btn, [{ label: "담당자 없음", icon: menuIcon("person_off"), checked: !r.assignee, onClick: function () { r.assignee = ""; save(); render(); } }, null]
|
||||
const set = function (e) { r.assignee = e; render(); persist(r, { assignee_email: e }); };
|
||||
menuAt(btn, [{ label: "담당자 없음", icon: menuIcon("person_off"), checked: !r.assignee, onClick: function () { set(""); } }, null]
|
||||
.concat(emails.map(function (e) {
|
||||
return { label: nameOf(e), icon: faceHtml(e), checked: r.assignee === e, onClick: function () { r.assignee = e; save(); render(); } };
|
||||
return { label: nameOf(e), icon: faceHtml(e), checked: r.assignee === e, onClick: function () { set(e); } };
|
||||
})));
|
||||
}
|
||||
async function pickStage(r, btn) {
|
||||
if (!r.projectId) { showToast("프로젝트를 먼저 고르세요."); return; }
|
||||
const stages = await stagesOf(r.projectId);
|
||||
menuAt(btn, stages.map(function (st) {
|
||||
return { label: st.name, icon: menuIcon("view_column"), checked: r.stageId === st.id, onClick: function () { r.stageId = st.id; r.stageName = st.name; save(); render(); } };
|
||||
}));
|
||||
const pid = r.projectId;
|
||||
const set = function (st) {
|
||||
r.stageId = st.id; r.stageName = st.name;
|
||||
const keepTask = r.parentTaskId && (taskCache[pid] || []).some(function (t) { return t.id === r.parentTaskId && t.stage_id === st.id; });
|
||||
if (!keepTask) { r.parentTaskId = null; r.parentTaskTitle = ""; }
|
||||
render(); persist(r, { project_id: pid, stage_id: st.id, parent_task_id: r.parentTaskId });
|
||||
};
|
||||
// 목록 맨 위 "+ 새 섹션" — 그 프로젝트 멤버 누구나(서버 POST …/stages). 만든 섹션을 바로 고른다.
|
||||
const head = [{ label: "새 섹션", icon: menuIcon("add"), onClick: async function () {
|
||||
const name = await prompt("‘" + r.projectName + "’에 만들 섹션 이름", "");
|
||||
if (name == null || !String(name).trim()) return;
|
||||
try {
|
||||
const res = await api("POST", "/project/api/projects/" + pid + "/stages", { name: String(name).trim() });
|
||||
(stageCache[pid] = stageCache[pid] || []).push(res.stage);
|
||||
if (r.projectId === pid) set(res.stage);
|
||||
showToast("섹션 ‘" + res.stage.name + "’를 만들었습니다.");
|
||||
} catch (e) { showToast("섹션 만들기 실패: " + e.message, "error"); }
|
||||
} }, null];
|
||||
// 완료 섹션(완료 단계)은 목록에서 뺀다 — 거기 만들면 바로 완료 처리된다
|
||||
menuAt(btn, head.concat(stages.filter(function (st) { return !st.is_done_stage; }).map(function (st) {
|
||||
return { label: st.name, icon: menuIcon("view_column"), checked: r.stageId === st.id, onClick: function () { set(st); } };
|
||||
})));
|
||||
}
|
||||
// 작업 칸 — 맨 위 "새 작업(섹션에)" + 그 섹션(섹션이 없으면 프로젝트 전체)의 미완료 메인 작업. 고르면 세부 작업으로 등록.
|
||||
async function pickTask(r, btn) {
|
||||
if (!r.projectId) { showToast("프로젝트를 먼저 고르세요."); return; }
|
||||
const pid = r.projectId;
|
||||
const all = await tasksOf(pid);
|
||||
const list = r.stageId ? all.filter(function (t) { return t.stage_id === r.stageId; }) : all;
|
||||
const set = function (t) {
|
||||
r.parentTaskId = t ? t.id : null; r.parentTaskTitle = t ? t.title : "";
|
||||
if (t && t.stage_id) {
|
||||
const st = (stageCache[pid] || []).find(function (x) { return x.id === t.stage_id; });
|
||||
if (st) { r.stageId = st.id; r.stageName = st.name; }
|
||||
}
|
||||
render(); persist(r, { parent_task_id: r.parentTaskId, stage_id: r.stageId });
|
||||
};
|
||||
menuAt(btn, [{ label: "새 작업" + (r.stageName ? " (‘" + r.stageName + "’ 섹션에)" : ""), icon: menuIcon("add_task"),
|
||||
checked: !r.parentTaskId, onClick: function () { set(null); } }, null]
|
||||
.concat(list.length ? list.map(function (t) {
|
||||
return { label: t.title, icon: menuIcon("subdirectory_arrow_right"), checked: r.parentTaskId === t.id, onClick: function () { set(t); } };
|
||||
}) : [{ label: r.stageName ? "이 섹션에 진행 중인 작업이 없습니다" : "진행 중인 작업이 없습니다", onClick: function () {} }]));
|
||||
}
|
||||
|
||||
async function apply(r, btn) {
|
||||
flushTitle(r);
|
||||
if (!r.title.trim()) { showToast("작업 제목을 쓰세요."); return; }
|
||||
if (!r.projectId) { showToast("프로젝트를 고르세요."); return; }
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await api("POST", "/project/api/projects/" + r.projectId + "/tasks", {
|
||||
title: r.title.trim(), stage_id: r.stageId, assignee_email: r.assignee || "",
|
||||
assignee_name: r.assignee ? nameOf(r.assignee) : "",
|
||||
});
|
||||
r.done = { id: res.task.id, pid: r.projectId };
|
||||
showToast("‘" + r.projectName + "’에 작업을 등록했습니다.");
|
||||
if (!rows.some(function (x) { return !x.done; })) rows.push(blank());
|
||||
save(); render();
|
||||
await r.chain;
|
||||
if (!r.id) await persist(r, {});
|
||||
if (!r.id) throw new Error("줄을 저장하지 못했습니다");
|
||||
const res = await api("POST", rowUrl(r.id) + "/apply", {});
|
||||
const sub = !!r.parentTaskId;
|
||||
Object.assign(r, fromServer(res.task));
|
||||
if (sub && taskCache[r.projectId]) delete taskCache[r.projectId];
|
||||
showToast(res.created ? (sub ? "‘" + r.parentTaskTitle + "’의 세부 작업으로 등록했습니다." : "‘" + r.projectName + "’에 작업을 등록했습니다.")
|
||||
: "이미 등록된 줄입니다(다른 사람이 먼저 [적용]했습니다).");
|
||||
delete taskCache[r.projectId]; // 새 작업이 작업 칸 후보에 보이게
|
||||
padBlank(); render();
|
||||
} catch (e) {
|
||||
btn.disabled = false;
|
||||
showToast("작업 등록 실패: " + e.message, "error");
|
||||
}
|
||||
}
|
||||
// 등록된 작업 삭제 — 프로젝트에서도 지운다(휴지통). 이미 없으면(다른 곳에서 삭제) 줄만 지운다.
|
||||
// 등록된 작업 삭제 — 프로젝트에서도 지운다(휴지통, 세부 작업 포함). 이미 없으면(다른 곳에서 삭제) 줄만 지운다.
|
||||
async function removeTask(r, btn) {
|
||||
if (!(await confirm("‘" + (r.title || "작업") + "’ 작업을 ‘" + (r.projectName || "프로젝트") + "’에서도 삭제할까요? 삭제한 작업은 휴지통에 3개월 보관됩니다.",
|
||||
if (r.taskExists && !(await confirm("‘" + (r.title || "작업") + "’ 작업을 프로젝트에서도 삭제할까요? 세부 작업도 함께, 휴지통에 3개월 보관됩니다.",
|
||||
{ okText: "삭제", cancelText: "취소" }))) return;
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await api("DELETE", "/project/api/tasks/" + r.done.id);
|
||||
showToast("작업을 삭제했습니다.");
|
||||
} catch (e) {
|
||||
if (e.status !== 404) { btn.disabled = false; showToast("작업 삭제 실패: " + e.message, "error"); return; }
|
||||
if (r.taskId && r.taskExists) {
|
||||
try { await api("DELETE", "/project/api/tasks/" + r.taskId); showToast("작업을 삭제했습니다."); }
|
||||
catch (e) { if (e.status !== 404) { btn.disabled = false; showToast("작업 삭제 실패: " + e.message, "error"); return; } }
|
||||
}
|
||||
dropRow(r);
|
||||
}
|
||||
function dropRow(r) {
|
||||
async function dropRow(r) {
|
||||
try {
|
||||
await r.chain;
|
||||
if (r.id) await api("DELETE", rowUrl(r.id));
|
||||
} catch (e) { if (e.status !== 404) { showToast("줄을 지우지 못했습니다: " + e.message, "error"); return; } }
|
||||
const i = rows.indexOf(r);
|
||||
if (i >= 0) rows.splice(i, 1);
|
||||
if (!rows.some(function (x) { return !x.done; })) rows.push(blank());
|
||||
save(); render();
|
||||
padBlank(); render();
|
||||
}
|
||||
|
||||
// ── 오른쪽 작업 창 — 등록된 줄의 제목을 누르면 그 작업 편집 창(프로젝트 화면 ?embed=1 을 iframe 에, 수신함과 같은 방식).
|
||||
// 다른 작업으로 바꾸거나 닫기 전에 작업 창 안의 저장을 기다린다(__pjEmbedSettle — 실패면 "버리고 넘어가기 / 계속 편집").
|
||||
let panel = null, panelTask = null, switching = null, wanted;
|
||||
function panelOpen() { return !!panel && panel.classList.contains("is-open"); }
|
||||
async function settleFrame() {
|
||||
if (!panelOpen()) return true;
|
||||
let fn = null;
|
||||
try { fn = panel.querySelector("iframe").contentWindow.__pjEmbedSettle; } catch (_) { fn = null; }
|
||||
if (typeof fn !== "function") return true;
|
||||
try { return !!(await fn()); } catch (_) { return false; }
|
||||
}
|
||||
function showPanel(taskId) {
|
||||
if (taskId == null) {
|
||||
if (!panelOpen()) return;
|
||||
panel.classList.remove("is-open");
|
||||
panelTask = null;
|
||||
const p = panel;
|
||||
setTimeout(function () { if (!p.classList.contains("is-open")) p.querySelector("iframe").src = "about:blank"; }, 250);
|
||||
load(true); // 작업 창에서 제목 등을 바꿨을 수 있다
|
||||
return;
|
||||
}
|
||||
if (!panel) {
|
||||
panel = document.createElement("div");
|
||||
panel.className = "pj-inbox-panel pj-meet-task-panel";
|
||||
panel.innerHTML = '<iframe title="작업"></iframe>';
|
||||
document.body.appendChild(panel); // 화면 배율(.pj-ui-scale) 밖 — body 에
|
||||
}
|
||||
panelTask = taskId;
|
||||
panel.querySelector("iframe").src = "/project/t/" + taskId + "?embed=1";
|
||||
void panel.offsetWidth;
|
||||
panel.classList.add("is-open");
|
||||
}
|
||||
function requestPanel(taskId) {
|
||||
wanted = taskId;
|
||||
if (switching) return switching;
|
||||
switching = (async function () {
|
||||
while (wanted !== undefined) {
|
||||
const t = wanted;
|
||||
if ((t === null && !panelOpen()) || (t !== null && panelOpen() && panelTask === t)) { wanted = undefined; break; }
|
||||
const ok = await settleFrame();
|
||||
if (!ok) { wanted = undefined; break; }
|
||||
if (wanted !== t) continue;
|
||||
wanted = undefined;
|
||||
showPanel(t);
|
||||
}
|
||||
})().finally(function () { switching = null; });
|
||||
return switching;
|
||||
}
|
||||
window.addEventListener("message", function (e) {
|
||||
if (e.origin === location.origin && e.data && e.data.type === "pj-embed-close" && panelOpen()) requestPanel(null);
|
||||
});
|
||||
document.addEventListener("keydown", function (e) { if (e.key === "Escape" && panelOpen() && !modal) requestPanel(null); });
|
||||
document.addEventListener("mousedown", function (e) {
|
||||
if (!panelOpen() || panel.contains(e.target)) return;
|
||||
if (e.target.closest && e.target.closest('[data-quick="open"], .pj-ctxmenu, .pj-modal, .erp-dialog')) return;
|
||||
requestPanel(null);
|
||||
});
|
||||
|
||||
// 제목 — 치는 동안 0.6초 멈추면, 칸을 떠나면 저장
|
||||
const titleTimers = new Map();
|
||||
function flushTitle(r) {
|
||||
const t = titleTimers.get(r);
|
||||
if (!t) return;
|
||||
clearTimeout(t); titleTimers.delete(r);
|
||||
persist(r, { title: r.title });
|
||||
}
|
||||
const rowOf = function (node) { const tr = node.closest("tr"); return tr && tr.dataset.i != null ? rows[+tr.dataset.i] : null; };
|
||||
tbody.addEventListener("input", function (e) {
|
||||
const inp = e.target.closest("input[data-field=title]");
|
||||
if (!inp) return;
|
||||
rows[+inp.closest("tr").dataset.i].title = inp.value;
|
||||
save();
|
||||
if (!inp || inp.readOnly) return;
|
||||
const r = rowOf(inp);
|
||||
r.title = inp.value;
|
||||
clearTimeout(titleTimers.get(r));
|
||||
titleTimers.set(r, setTimeout(function () { titleTimers.delete(r); persist(r, { title: r.title }); }, 600));
|
||||
});
|
||||
tbody.addEventListener("focusout", function (e) {
|
||||
const inp = e.target.closest("input[data-field=title]");
|
||||
if (inp) { const r = rowOf(inp); if (r) flushTitle(r); }
|
||||
});
|
||||
tbody.addEventListener("keydown", function (e) {
|
||||
const inp = e.target.closest("input[data-field=title]");
|
||||
if (inp && e.key === "Enter" && !isImeEnter(e)) { e.preventDefault(); inp.closest("tr").querySelector('[data-pick="assignee"]').click(); }
|
||||
if (inp && !inp.readOnly && e.key === "Enter" && !isImeEnter(e)) {
|
||||
e.preventDefault();
|
||||
flushTitle(rowOf(inp));
|
||||
inp.closest("tr").querySelector('[data-pick="assignee"]').click();
|
||||
}
|
||||
});
|
||||
tbody.addEventListener("click", function (e) {
|
||||
const tr = e.target.closest("tr");
|
||||
if (!tr) return;
|
||||
if (!tr || tr.dataset.i == null) return;
|
||||
const r = rows[+tr.dataset.i], pick = e.target.closest("[data-pick]");
|
||||
const del = e.target.closest('[data-quick="delete"], [data-quick="remove"]');
|
||||
if (del) { if (del.dataset.quick === "delete") removeTask(r, del); else dropRow(r); return; }
|
||||
if (r.done) return;
|
||||
if (e.target.closest('[data-quick="open"]')) { if (modal) closeBig(); requestPanel(r.taskId); return; }
|
||||
if (r.registered || locked) return;
|
||||
const fail = function (err) { showToast("목록을 읽지 못했습니다: " + err.message, "error"); };
|
||||
if (pick) {
|
||||
e.stopPropagation();
|
||||
({ project: pickProject, assignee: pickAssignee, stage: pickStage })[pick.dataset.pick](r, pick).catch(fail);
|
||||
({ project: pickProject, assignee: pickAssignee, stage: pickStage, task: pickTask })[pick.dataset.pick](r, pick).catch(fail);
|
||||
} else if (e.target.closest('[data-quick="apply"]')) apply(r, e.target.closest('[data-quick="apply"]'));
|
||||
});
|
||||
box.querySelector('[data-quick="add"]').addEventListener("click", function () { rows.push(blank()); save(); render(); });
|
||||
render();
|
||||
const addBtn = box.querySelector('[data-quick="add"]');
|
||||
if (addBtn) {
|
||||
if (locked) addBtn.hidden = true;
|
||||
else addBtn.addEventListener("click", function () {
|
||||
const b = blank(); rows.push(b); render();
|
||||
const inp = tbody.querySelector('tr[data-i="' + rows.indexOf(b) + '"] input[data-field="title"]');
|
||||
if (inp) inp.focus();
|
||||
});
|
||||
}
|
||||
|
||||
// ── 크게 열기 — 같은 표(같은 줄·같은 저장)를 넓은 창으로 옮겨 쓴다. 닫으면 제자리로 ──
|
||||
const area = box.querySelector(".pj-meet-area-body");
|
||||
const expandBtn = box.querySelector('[data-quick="expand"]');
|
||||
let modal = null;
|
||||
function closeBig() {
|
||||
if (!modal) return;
|
||||
box.appendChild(area);
|
||||
modal.remove(); modal = null;
|
||||
document.removeEventListener("keydown", onBigKey, true);
|
||||
if (expandBtn) expandBtn.focus();
|
||||
}
|
||||
function onBigKey(e) {
|
||||
if (e.key === "Escape" && modal && !document.querySelector(".pj-ctxmenu, .pj-modal:not([hidden])")) { e.preventDefault(); e.stopPropagation(); closeBig(); }
|
||||
}
|
||||
function openBig() {
|
||||
if (modal) return;
|
||||
modal = document.createElement("div");
|
||||
modal.className = "pj-meet-quick-modal";
|
||||
modal.innerHTML = '<div class="pj-meet-quick-modal-card" role="dialog" aria-modal="true" aria-label="작업 등록 크게 보기">' +
|
||||
'<div class="pj-meet-quick-modal-head"><h3></h3><button type="button" class="pj-icon-btn" data-quick="close-big" title="닫기 (Esc)">' +
|
||||
'<span class="material-symbols-outlined">close</span></button></div></div>';
|
||||
const wk = box.querySelector(".pj-meet-quick-week");
|
||||
modal.querySelector("h3").textContent = (wk ? wk.textContent + " " : "") + "작업 등록";
|
||||
modal.querySelector(".pj-meet-quick-modal-card").appendChild(area);
|
||||
document.body.appendChild(modal); // 화면 배율(.pj-ui-scale) 밖 — body 에
|
||||
modal.addEventListener("mousedown", function (e) { if (e.target === modal) closeBig(); });
|
||||
modal.querySelector('[data-quick="close-big"]').addEventListener("click", closeBig);
|
||||
document.addEventListener("keydown", onBigKey, true);
|
||||
const first = area.querySelector('input[data-field="title"]:not([readonly])');
|
||||
if (first) first.focus();
|
||||
}
|
||||
if (expandBtn) expandBtn.addEventListener("click", openBig);
|
||||
|
||||
// ── 읽기 — 처음·30초마다·창을 다시 볼 때. 입력 중(제목 칸 포커스·저장 대기)이면 건너뛴다 ──
|
||||
function busy() {
|
||||
return titleTimers.size > 0 || pendingSaves > 0 || (document.activeElement && tbody.contains(document.activeElement));
|
||||
}
|
||||
async function load(force) {
|
||||
if (!force && busy()) return;
|
||||
try {
|
||||
const res = await api("GET", listUrl);
|
||||
const blanks = rows.filter(function (r) { return !r.id && !r.title && !r.projectId && !r.assignee; }).length;
|
||||
rows = (res.tasks || []).map(fromServer);
|
||||
for (let i = 0; i < blanks; i++) rows.push(blank());
|
||||
padBlank();
|
||||
unavailable = "";
|
||||
ready = true;
|
||||
} catch (e) {
|
||||
if (e.status === 503) unavailable = e.message;
|
||||
else if (!ready) unavailable = "작업 등록 표를 읽지 못했습니다: " + e.message;
|
||||
}
|
||||
render();
|
||||
}
|
||||
// 이 브라우저에 남은 예전 표(주차 키 또는 주차 없는 예전 키 — 이번 주만) → 서버로 한 번 옮기고 지운다
|
||||
async function migrateLocal() {
|
||||
let key = LOCAL_KEY, raw = null;
|
||||
try {
|
||||
raw = localStorage.getItem(LOCAL_KEY);
|
||||
if (raw == null && box.dataset.now === "1") { raw = localStorage.getItem(LEGACY_KEY); key = LEGACY_KEY; }
|
||||
} catch (_) { return; }
|
||||
if (raw == null) return;
|
||||
let list = [];
|
||||
try { list = (JSON.parse(raw) || []).filter(function (r) { return r && (r.done || r.title || r.projectId || r.assignee); }); } catch (_) {}
|
||||
let failed = 0;
|
||||
for (const r of list) {
|
||||
const body = { title: r.title || "", assignee_email: r.assignee || "", project_id: r.projectId || null,
|
||||
stage_id: r.stageId || null, task_id: r.done ? r.done.id : null };
|
||||
try { await api("POST", listUrl, body); }
|
||||
catch (e) {
|
||||
if (e.status === 503) return; // 025 전 — 다음에 다시
|
||||
try { await api("POST", listUrl, { title: body.title, assignee_email: body.assignee_email }); }
|
||||
catch (_) { failed++; }
|
||||
}
|
||||
}
|
||||
try { localStorage.removeItem(key); } catch (_) {}
|
||||
if (list.length) showToast("이 브라우저에만 있던 작업 등록 줄 " + (list.length - failed) + "개를 모두가 보는 표로 옮겼습니다.");
|
||||
}
|
||||
(async function () {
|
||||
rows = [];
|
||||
padBlank(); render();
|
||||
await load(true);
|
||||
if (!unavailable && !locked) { await migrateLocal(); await load(true); }
|
||||
})();
|
||||
setInterval(function () { if (!document.hidden && ready && !panelOpen()) load(false); }, 30000);
|
||||
document.addEventListener("visibilitychange", function () { if (!document.hidden && ready && !panelOpen()) load(false); });
|
||||
if (window.__PJ_TEST__) window.__pjMeetQuick = { load: load, rows: function () { return rows; }, openBig: openBig, closeBig: closeBig,
|
||||
settling: function () { return switching || Promise.resolve(); } };
|
||||
}
|
||||
|
||||
function initGoalMeeting() {
|
||||
@@ -11069,7 +11409,10 @@
|
||||
return ta.dataset.field === "result_note" ? "meet:item:" + tr.dataset.prev + ":result_note"
|
||||
: "meet:item:" + tr.dataset.item + ":content";
|
||||
},
|
||||
onSaved: function (ta) { const n = ta.closest("td") || ta; clearSaveFailed(n); flashSaved(n); },
|
||||
onSaved: function (ta) {
|
||||
const n = ta.closest("td") || ta; clearSaveFailed(n); flashSaved(n);
|
||||
if (pendingMeetRefresh && !textSaver.anyDirty()) refreshMeeting().catch(function (err) { showToast(err.message, "error"); });
|
||||
},
|
||||
onClear: function (ta) { clearSaveFailed(ta.closest("td") || ta); },
|
||||
onFail: function (ta, err) { markSaveFailed(ta.closest("td") || ta, err); },
|
||||
});
|
||||
@@ -11094,8 +11437,11 @@
|
||||
if (table) table.querySelectorAll(".pj-meet-text, .pj-meet-rnote").forEach(bindText);
|
||||
if (cellGrid) cellGrid.bindSaver({ flush: flushAll, save: function (ta) { return textSaver.flush(ta); },
|
||||
replace: function (ta, value) { ta.value = value; textSaver.acceptSaved(ta, ta.value); },
|
||||
rowMenu: rowMenu, addRow: function (section, ref, place) { run(function () { return addRow(section, ref, place); }); },
|
||||
reload: reloadKeepScroll });
|
||||
rowMenu: rowMenu,
|
||||
// 주요 업무 칸 메뉴 — 위/아래 줄 추가는 같은 항목 칸 안에(027, 이름을 묻지 않음), 줄 삭제
|
||||
addRow: function (section, ref, place, o) { run(function () { return addRow(section, ref, place, o && o.sameLabel); }); },
|
||||
deleteRow: function (tr) { run(function () { return deleteRow(tr); }); },
|
||||
reload: function () { refreshMeeting().catch(function (err) { showToast("처리 실패: " + err.message, "error"); }); } });
|
||||
if (table && window.PJGoalText) window.PJGoalText.init(table, el("pj-goal-format"));
|
||||
if (restored) showToast("저장되지 않았던 글 " + restored + "칸을 되살려 다시 저장합니다.");
|
||||
else if (conflict) showToast("다른 곳에서 바뀐 칸 " + conflict + "개는 예전 초안을 되살리지 않았습니다.");
|
||||
@@ -11161,41 +11507,170 @@
|
||||
span.addEventListener("blur", onBlur);
|
||||
});
|
||||
|
||||
// ── 줄 메뉴(⋯ · 항목 우클릭) — 위/아래 줄 추가 · 순서 · 삭제 ──
|
||||
// 줄 작업 뒤엔 새로고침 — 그 전에 저장 안 된 칸(대기·진행 중·실패)을 저장하고, 실패하면 작업 자체를 하지 않는다(초안 유지)
|
||||
async function run(fn) {
|
||||
try {
|
||||
await flushAll();
|
||||
if (!(await fn())) return;
|
||||
await flushAll();
|
||||
reloadKeepScroll();
|
||||
} catch (err) { showToast("처리 실패: " + err.message, "error"); }
|
||||
// ── 줄 메뉴(⋯ · 항목 우클릭) — 위/아래 줄 추가 · 순서 · 항목 칸 나누기 · 삭제 ──
|
||||
// 줄 작업 전에 저장 안 된 칸(대기·진행 중·실패)을 저장하고, 실패하면 작업 자체를 하지 않는다(초안 유지).
|
||||
// 작업 뒤엔 새로고침 대신 표만 그 자리에서 다시 그린다(refreshMeeting — 연간 목표 표와 같은 애니메이션).
|
||||
// fn 이 true 면 다시 그리기, { removed: [tr…] } 면 그 줄을 흐리게 지운 뒤 다시 그리기, false 면 아무것도 안 함.
|
||||
let meetStruct = Promise.resolve();
|
||||
function run(fn) {
|
||||
const job = meetStruct.then(async function () { // 줄 작업은 한 번에 하나씩(앞 작업 다시 그리기가 끝난 뒤)
|
||||
try {
|
||||
await flushAll();
|
||||
const r = await fn();
|
||||
if (!r) return;
|
||||
await flushAll();
|
||||
await refreshMeeting(r === true ? {} : r);
|
||||
} catch (err) { showToast("처리 실패: " + err.message, "error"); }
|
||||
});
|
||||
meetStruct = job;
|
||||
return job;
|
||||
}
|
||||
async function addRow(section, ref, place) {
|
||||
// sameLabel(주요 업무 칸에서) = 기준 줄과 같은 항목 칸 안에 — 이름을 묻지 않는다(027)
|
||||
async function addRow(section, ref, place, sameLabel) {
|
||||
if (sameLabel) {
|
||||
await api("POST", meetingUrl + "/items", { section: section, label: "", ref_item_id: ref, place: place, same_label: true });
|
||||
return true;
|
||||
}
|
||||
const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", "");
|
||||
if (v == null) return false;
|
||||
await api("POST", meetingUrl + "/items", { section: section, label: String(v).trim(), ref_item_id: ref, place: place });
|
||||
return true;
|
||||
}
|
||||
// 항목 칸 묶음의 첫 줄(이어 붙은 줄이면 위로 거슬러 올라감)·맨 아래 줄
|
||||
function groupHead(tr) {
|
||||
let r = tr;
|
||||
while (r && r.dataset.labelCont === "1" && r.previousElementSibling) r = r.previousElementSibling;
|
||||
return r;
|
||||
}
|
||||
function groupBottom(tr) {
|
||||
const head = groupHead(tr), th = head.querySelector("th.pj-meet-c-label");
|
||||
const rows = Array.from(head.closest("tbody").rows);
|
||||
return rows[Math.min(rows.length - 1, rows.indexOf(head) + ((th && th.rowSpan) || 1) - 1)];
|
||||
}
|
||||
async function deleteRow(tr) {
|
||||
const head = groupHead(tr);
|
||||
const label = ((head.querySelector(".pj-meet-label") || {}).textContent || "").trim();
|
||||
const grouped = groupBottom(tr) !== head;
|
||||
const msg = !grouped ? "'" + (label || "이 줄") + "' 줄을 삭제할까요? 주요 업무·금액도 함께 삭제됩니다."
|
||||
: tr === head ? "'" + (label || "이 항목") + "' 항목의 첫 줄을 삭제할까요? 주요 업무·금액도 함께 삭제되고, 아래 줄이 항목 이름을 이어받습니다."
|
||||
: "'" + (label || "이 항목") + "' 항목의 이 줄을 삭제할까요? 주요 업무·금액도 함께 삭제됩니다.";
|
||||
const ok = await confirm(msg, { okText: "삭제", cancelText: "취소" });
|
||||
if (!ok) return false;
|
||||
await api("DELETE", itemUrl(tr.dataset.item));
|
||||
return { removed: [tr] };
|
||||
}
|
||||
function rowMenu(x, y, tr) {
|
||||
const id = tr.dataset.item, section = tr.dataset.section;
|
||||
const label = (tr.querySelector(".pj-meet-label") || {}).textContent || "";
|
||||
showContextMenu(x, y, [
|
||||
tr = groupHead(tr);
|
||||
const id = tr.dataset.item, section = tr.dataset.section, bottom = groupBottom(tr);
|
||||
const grouped = bottom !== tr;
|
||||
// 항목 칸에서 추가 = 항목 칸 밖에 따로(묶음 맨 위·맨 아래 기준). 묶인 칸은 순서 대신 "항목 칸 나누기"
|
||||
const items = [
|
||||
{ label: "위에 줄 추가", icon: menuIcon("add_row_above"), onClick: function () { run(function () { return addRow(section, id, "above"); }); } },
|
||||
{ label: "아래에 줄 추가", icon: menuIcon("add_row_below"), onClick: function () { run(function () { return addRow(section, id, "below"); }); } },
|
||||
{ label: "위로", icon: menuIcon("arrow_upward"), onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: -1 }); return true; }); } },
|
||||
{ label: "아래로", icon: menuIcon("arrow_downward"), onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: 1 }); return true; }); } },
|
||||
null,
|
||||
{ label: "줄 삭제", danger: true, icon: menuIcon("delete"), onClick: function () {
|
||||
run(async function () {
|
||||
const ok = await confirm("'" + (label.trim() || "이 줄") + "' 줄을 삭제할까요? 주요 업무·금액도 함께 삭제됩니다.",
|
||||
{ okText: "삭제", cancelText: "취소" });
|
||||
if (!ok) return false;
|
||||
await api("DELETE", itemUrl(id));
|
||||
return true;
|
||||
{ label: "아래에 줄 추가", icon: menuIcon("add_row_below"), onClick: function () { run(function () { return addRow(section, bottom.dataset.item, "below"); }); } },
|
||||
];
|
||||
if (grouped) {
|
||||
items.push({ label: "항목 칸 나누기", icon: menuIcon("horizontal_split"), onClick: function () {
|
||||
run(async function () { await api("POST", itemUrl(id) + "/split-label"); return true; });
|
||||
} });
|
||||
} else {
|
||||
items.push(
|
||||
{ label: "위로", icon: menuIcon("arrow_upward"), onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: -1 }); return true; }); } },
|
||||
{ label: "아래로", icon: menuIcon("arrow_downward"), onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: 1 }); return true; }); } });
|
||||
}
|
||||
items.push(null, { label: grouped ? "첫 줄 삭제" : "줄 삭제", danger: true, icon: menuIcon("delete"), onClick: function () {
|
||||
run(function () { return deleteRow(tr); });
|
||||
} });
|
||||
showContextMenu(x, y, items.concat(cellGrid ? [null].concat(cellGrid.widthItems(tr.querySelector("th.pj-meet-c-label"))) : []));
|
||||
}
|
||||
|
||||
// ── 줄 구조가 바뀐 뒤(줄 추가·삭제·이동·항목 칸 나누기·구역 이동·셀 병합) 새로고침 없이 표의 구역 부분만 서버에서 다시 받아
|
||||
// 그 자리에서 바꿔 끼운다(연간 목표 refreshTable 과 같은 방식) — 지운 줄은 흐려지며 사라지고, 남은 줄은 예전 자리에서
|
||||
// 새 자리로 미끄러지고(FLIP), 새 줄은 위에서 내려오며 잠깐 강조. 동작 줄이기 설정이면 애니메이션 없이.
|
||||
// 글 보호: 시작 전에 저장(실패하면 throw — 표는 그대로), 받는 사이에 새로 입력한 글이 있으면 저장 후 다시 받고,
|
||||
// 계속 입력 중이면 바꿔 끼우지 않고 저장이 끝난 뒤 다시 그린다(pendingMeetRefresh). 받아 오기에 실패하면 예전처럼 새로고침.
|
||||
const MEET_ANIM_MS = 280;
|
||||
let pendingMeetRefresh = false;
|
||||
async function refreshMeeting(opts) {
|
||||
opts = opts || {};
|
||||
await flushAll();
|
||||
const reduce = !Element.prototype.animate ||
|
||||
(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
|
||||
const busy = function () {
|
||||
return textSaver.anyDirty() || amtSaver.anyDirty() || !!table.querySelector("[data-meet-edit].is-editing");
|
||||
};
|
||||
let fresh = null, anims = [];
|
||||
for (let tries = 0; ; tries++) {
|
||||
fresh = null;
|
||||
try {
|
||||
const res = await fetch(location.href, { credentials: "same-origin", cache: "no-store" });
|
||||
if (res.ok) fresh = new DOMParser().parseFromString(await res.text(), "text/html").getElementById("pj-meet-table");
|
||||
} catch (_) { fresh = null; }
|
||||
if (!busy() && opts.removed && opts.removed.length && !reduce && !anims.length) {
|
||||
anims = opts.removed.filter(function (tr) { return tr.isConnected; }).map(function (tr) {
|
||||
return tr.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 180, easing: "ease-in", fill: "forwards" });
|
||||
});
|
||||
} },
|
||||
].concat(cellGrid ? [null].concat(cellGrid.widthItems(tr.querySelector("th.pj-meet-c-label"))) : []));
|
||||
await Promise.all(anims.map(function (a) { return a.finished.catch(function () {}); }));
|
||||
}
|
||||
if (!busy()) break;
|
||||
anims.forEach(function (a) { try { a.cancel(); } catch (_) {} });
|
||||
anims = [];
|
||||
if (tries >= 2) {
|
||||
pendingMeetRefresh = true;
|
||||
showToast("입력 중인 칸이 있어 표를 아직 다시 그리지 않았습니다 — 저장되면 다시 그립니다.");
|
||||
return;
|
||||
}
|
||||
await flushAll(); // 받는 동안 새로 입력한 글 — 저장 실패면 throw(표는 그대로)
|
||||
}
|
||||
if (!fresh) { reloadKeepScroll(); return; }
|
||||
pendingMeetRefresh = false;
|
||||
const before = new Map();
|
||||
table.querySelectorAll("tbody.pj-meet-sec > tr[data-item]").forEach(function (tr) {
|
||||
before.set(tr.dataset.item, tr.getBoundingClientRect().top);
|
||||
});
|
||||
table.querySelectorAll("tbody.pj-meet-sec").forEach(function (t) { t.remove(); });
|
||||
fresh.querySelectorAll("tbody.pj-meet-sec").forEach(function (t) { table.appendChild(document.importNode(t, true)); });
|
||||
textSaver.prune();
|
||||
amtSaver.prune();
|
||||
table.querySelectorAll(".pj-meet-text, .pj-meet-rnote").forEach(bindText);
|
||||
table.querySelectorAll("input.pj-meet-amount").forEach(bindAmount);
|
||||
table.dispatchEvent(new CustomEvent("pj-meet-rows")); // 이번주 ↔ 지난주 칸 순서(initMeetOrder)
|
||||
if (cellGrid && cellGrid.refresh) cellGrid.refresh(); // 열 너비 손잡이·이동 테두리·선택
|
||||
if (reduce) return;
|
||||
table.querySelectorAll("tbody.pj-meet-sec > tr[data-item]").forEach(function (tr) {
|
||||
const top = tr.getBoundingClientRect().top;
|
||||
if (before.has(tr.dataset.item)) {
|
||||
const dy = before.get(tr.dataset.item) - top;
|
||||
if (Math.abs(dy) > 1) {
|
||||
tr.animate([{ transform: "translateY(" + dy + "px)" }, { transform: "translateY(0)" }],
|
||||
{ duration: MEET_ANIM_MS, easing: "cubic-bezier(.2,.8,.2,1)" });
|
||||
}
|
||||
} else {
|
||||
tr.animate([{ opacity: 0, transform: "translateY(-10px)" }, { opacity: 1, transform: "translateY(0)" }],
|
||||
{ duration: MEET_ANIM_MS + 40, easing: "cubic-bezier(.2,.8,.2,1)" });
|
||||
tr.classList.add("is-new-row");
|
||||
setTimeout(function () { tr.classList.remove("is-new-row"); }, 1400);
|
||||
}
|
||||
});
|
||||
}
|
||||
// ── 구역 메뉴(구분 칸 ⋯ · 우클릭) — 구역을 통째로 위/아래(그 안의 줄 순서·병합은 그대로), 구역 끝에 줄 추가 ──
|
||||
function secMenu(x, y, tbody) {
|
||||
const blocks = Array.prototype.slice.call(table.querySelectorAll("tbody.pj-meet-sec"));
|
||||
const i = blocks.indexOf(tbody);
|
||||
const first = tbody.querySelector("tr[data-item]");
|
||||
if (!first) return;
|
||||
const mv = function (dir) {
|
||||
return function () {
|
||||
run(async function () { await api("POST", itemUrl(first.dataset.item) + "/move-section", { direction: dir }); return true; });
|
||||
};
|
||||
};
|
||||
const items = [];
|
||||
if (i > 0) items.push({ label: "구역 위로", icon: menuIcon("arrow_upward"), onClick: mv(-1) });
|
||||
if (i < blocks.length - 1) items.push({ label: "구역 아래로", icon: menuIcon("arrow_downward"), onClick: mv(1) });
|
||||
if (items.length) items.push(null);
|
||||
items.push({ label: "구역 끝에 줄 추가", icon: menuIcon("add_row_below"), onClick: function () {
|
||||
run(function () { return addRow(tbody.dataset.section, null, "below"); });
|
||||
} });
|
||||
showContextMenu(x, y, items);
|
||||
}
|
||||
table.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("[data-meet-act]");
|
||||
@@ -11204,13 +11679,23 @@
|
||||
if (b.dataset.meetAct === "menu") {
|
||||
const r = b.getBoundingClientRect();
|
||||
rowMenu(r.left, r.bottom + 4, tr);
|
||||
} else if (b.dataset.meetAct === "sec-menu") {
|
||||
const r = b.getBoundingClientRect();
|
||||
secMenu(r.left, r.bottom + 4, b.closest("tbody"));
|
||||
} else if (b.dataset.meetAct === "sec-add") {
|
||||
run(function () { return addRow(b.closest("tbody").dataset.section, null, "below"); });
|
||||
}
|
||||
});
|
||||
table.addEventListener("contextmenu", function (e) {
|
||||
if (e.target.closest(".is-editing")) return;
|
||||
const sec = e.target.closest("tbody.pj-meet-sec th.pj-meet-c-sec");
|
||||
if (sec && canEdit) {
|
||||
e.preventDefault();
|
||||
secMenu(e.clientX, e.clientY, sec.closest("tbody"));
|
||||
return;
|
||||
}
|
||||
const th = e.target.closest("th.pj-meet-c-label");
|
||||
if (!th || e.target.closest(".is-editing")) return;
|
||||
if (!th) return;
|
||||
e.preventDefault();
|
||||
rowMenu(e.clientX, e.clientY, th.closest("tr"));
|
||||
});
|
||||
@@ -11345,7 +11830,15 @@
|
||||
poll();
|
||||
}
|
||||
|
||||
// 다른 화면이 프로젝트 부품을 같이 쓴다(긴급 공지 관리 — app/modules/notice): 설명 편집기(서식 도구 전체·이미지)·
|
||||
// 아사나식 날짜 팝업·멤버 고르기(아이콘 + 이름)·알림. window.PJ_LIB_ONLY 면 프로젝트 화면 초기화는 하지 않고
|
||||
// 공용 말풍선만 켠다(프로젝트 알림 팝업 확인·실시간 동기화 등이 그 화면에서 돌지 않게).
|
||||
window.PJLib = {
|
||||
createDescEditor: createDescEditor, enhanceDateInput: enhanceDateInput,
|
||||
memberPickHtml: memberPickHtml, showToast: showToast,
|
||||
};
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
if (window.PJ_LIB_ONLY) { initHoverTips(); return; }
|
||||
// 좌측 프로젝트 목록 — 프로젝트 화면은 initProject 가 자기 데이터로 직접 연다.
|
||||
if (!document.querySelector(".pj-project-view")) initSideTree();
|
||||
initTrash();
|
||||
|
||||
@@ -340,5 +340,8 @@
|
||||
: `총 ${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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<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" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
</head>
|
||||
<body class="erp-body erp-app-body">
|
||||
@@ -95,6 +96,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 +190,8 @@
|
||||
인라인 스크립트가 곧바로 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 %}
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -167,5 +167,8 @@
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -125,6 +125,67 @@ 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';"
|
||||
```
|
||||
|
||||
## 실적 수동 입력·열 순서 마이그레이션 (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;"
|
||||
```
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (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 실데이터 대조 전), 나머지 4개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||
|
||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||
@@ -183,6 +183,36 @@
|
||||
+ 주문 상태별·클레임·정산 항목 합계. 화면 숫자와 다르면 출처별 열로 어느 쪽이 빠졌는지 본다.
|
||||
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||
|
||||
### 쿠팡 (`adapters/coupang.py`, 구현됨 — 규칙 대조 전)
|
||||
|
||||
- 맞출 화면(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`).
|
||||
로켓그로스만 거부돼도 판매자배송 결과는 보인다.
|
||||
|
||||
### 수동 입력(마이그레이션 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 안내.
|
||||
- 열 순서(002 + `registry.py`): 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON.
|
||||
- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`).
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
|
||||
@@ -1191,6 +1191,49 @@ 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장 관리자 보고 정책).
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -62,9 +62,11 @@ 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
|
||||
@@ -74,13 +76,13 @@ 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)
|
||||
('toss', '토스쇼핑', 40),
|
||||
('gsshop', 'GS샵', 50),
|
||||
('elevenst', '11번가', 60),
|
||||
('ohouse', '오늘의집', 70),
|
||||
('gmarket', 'G마켓', 80),
|
||||
('kakao', '카카오', 90),
|
||||
('lotteon', '롯데ON', 100)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
@@ -208,13 +210,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;
|
||||
@@ -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,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,145 @@
|
||||
// 실적 — 수동 입력(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 body = o && o.body ? JSON.parse(o.body) : null;
|
||||
e.calls.push({ method: method, url: url, body: body });
|
||||
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_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("[설정] 쇼핑몰 순서 = 표 순서", rows.join(",") === "cafe24,naver,coupang,toss,gsshop,elevenst,ohouse,gmarket,kakao,lotteon", 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);
|
||||
})();
|
||||
@@ -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,84 @@
|
||||
"""실적 대시보드(index.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_performance.py # → tests/js/.out/perf_dash.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.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 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)
|
||||
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()
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""긴급 공지 — 검증(본문 정리·이미지 형식·시각·받는 사람)과 API 권한(수퍼관리자만 만들기, 받는 사람만 확인·이미지). DB 없이."""
|
||||
import importlib
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.notice import store
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
from app.timezone import KST
|
||||
|
||||
api = importlib.import_module("app.modules.notice.router")
|
||||
|
||||
SUPER = {"email": SUPER_ADMIN_EMAIL, "name": "King", "is_super_admin": True}
|
||||
ADMIN = {"email": "admin@test.local", "role": "admin"}
|
||||
BOB = {"email": "bob@test.local"}
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 20
|
||||
|
||||
|
||||
class ValidationTests(unittest.TestCase):
|
||||
def test_body_keeps_only_notice_images(self):
|
||||
html = ('<p>점검 <b>안내</b></p><img src="/notice/images/7" alt="a"><img src="https://evil.example/x.png">'
|
||||
'<img src="data:image/png;base64,AAAA"><script>alert(1)</script><a href="javascript:alert(1)">x</a>')
|
||||
out = store.sanitize_body(html)
|
||||
self.assertIn('/notice/images/7', out)
|
||||
self.assertNotIn("evil.example", out)
|
||||
self.assertNotIn("data:image", out)
|
||||
self.assertNotIn("<script", out)
|
||||
self.assertNotIn("javascript:", out)
|
||||
self.assertIn("<b>안내</b>", out)
|
||||
self.assertEqual(store.image_ids_in(out), [7])
|
||||
|
||||
def test_title_targets_time(self):
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_title(" ")
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_title("x" * 201)
|
||||
self.assertEqual(store.validate_targets(True, ["a@b"]), (True, []))
|
||||
self.assertEqual(store.validate_targets(False, ["A@Test.local", "a@test.local", "nope"]), (False, ["a@test.local"]))
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_targets(False, [])
|
||||
d = store.parse_show_at("2026-10-12T18:30")
|
||||
self.assertEqual((d.hour, d.minute, d.utcoffset()), (18, 30, timedelta(hours=9))) # 화면 입력 = 한국시간
|
||||
self.assertEqual(store.parse_show_at("2026-10-12T09:30:00Z").astimezone(KST).hour, 18)
|
||||
self.assertLess(abs((store.parse_show_at("") - datetime.now(KST)).total_seconds()), 5)
|
||||
with self.assertRaises(ValueError):
|
||||
store.parse_show_at("내일")
|
||||
|
||||
def test_image_sniffing(self):
|
||||
self.assertEqual(store.sniff_image(PNG), "image/png")
|
||||
self.assertEqual(store.sniff_image(b"\xff\xd8\xff\xe0abc"), "image/jpeg")
|
||||
self.assertEqual(store.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp")
|
||||
for bad in (b"", b"<svg onload=alert(1)>", b"<html>", b"\x89PNG" + b"0" * (store.IMAGE_MAX_BYTES)):
|
||||
with self.assertRaises(ValueError):
|
||||
store.sniff_image(bad)
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
now = datetime.now(KST)
|
||||
self.notices = {
|
||||
1: {"id": 1, "title": "전체 공지", "body_html": "<p>x</p>", "show_at": now.isoformat(), "to_all": True,
|
||||
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []},
|
||||
2: {"id": 2, "title": "일부", "body_html": "", "show_at": now.isoformat(), "to_all": False,
|
||||
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": ["carol@test.local"]},
|
||||
3: {"id": 3, "title": "예약", "body_html": "", "show_at": (now + timedelta(hours=1)).isoformat(), "to_all": True,
|
||||
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []},
|
||||
}
|
||||
self.images = {5: {"id": 5, "notice_id": 2, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL},
|
||||
6: {"id": 6, "notice_id": 3, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL}}
|
||||
self.acked, self.created = [], []
|
||||
|
||||
def enabled(self):
|
||||
return True
|
||||
|
||||
def pending_for(self, email):
|
||||
return [n for n in self.notices.values() if self.is_recipient(notice=n, email=email)]
|
||||
|
||||
def get_notice(self, notice_id):
|
||||
return self.notices.get(notice_id)
|
||||
|
||||
def is_recipient(self, notice, email):
|
||||
return notice["to_all"] or email in notice["targets"]
|
||||
|
||||
def ack(self, notice_id, email):
|
||||
self.acked.append((notice_id, email))
|
||||
return True
|
||||
|
||||
def list_notices(self):
|
||||
return [{**n, "acks": {}} for n in self.notices.values()]
|
||||
|
||||
def create_notice(self, **kw):
|
||||
self.created.append(kw)
|
||||
store.validate_title(kw["title"])
|
||||
return {"id": 9, **kw}
|
||||
|
||||
def get_image(self, image_id):
|
||||
return self.images.get(image_id)
|
||||
|
||||
def add_image(self, data, filename, by):
|
||||
return {"id": 10, "url": "/notice/images/10", "content_type": store.sniff_image(data)}
|
||||
|
||||
|
||||
class NoticeApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
self.st = FakeStore()
|
||||
app.state.notice_store = self.st
|
||||
self.client = TestClient(app)
|
||||
|
||||
def as_(self, who):
|
||||
fake = types.ModuleType("app.main")
|
||||
fake.get_current_user_record = lambda request: who
|
||||
return patch.dict(sys.modules, {"app.main": fake})
|
||||
|
||||
def test_only_super_admin_manages(self):
|
||||
body = {"title": "t", "body_html": "", "to_all": True}
|
||||
for who in (ADMIN, BOB):
|
||||
with self.as_(who):
|
||||
self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 403)
|
||||
self.assertEqual(self.client.get("/notice/api/notices").status_code, 403)
|
||||
self.assertEqual(self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")}).status_code, 403)
|
||||
with self.as_(SUPER):
|
||||
self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 201)
|
||||
self.assertEqual(self.client.post("/notice/api/notices", json={"title": ""}).status_code, 400)
|
||||
r = self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")})
|
||||
self.assertEqual((r.status_code, r.json()["image"]["url"]), (201, "/notice/images/10"))
|
||||
self.assertEqual(self.client.post("/notice/api/images", files={"file": ("x.svg", b"<svg/>", "image/svg+xml")}).status_code, 400)
|
||||
with self.as_(None):
|
||||
self.assertEqual(self.client.get("/notice/api/pending").status_code, 401)
|
||||
|
||||
def test_pending_hides_admin_fields_and_ack_only_for_recipients(self):
|
||||
with self.as_(BOB):
|
||||
out = self.client.get("/notice/api/pending").json()["notices"]
|
||||
self.assertEqual(sorted(n["id"] for n in out), [1, 3]) # 시각 판단은 저장소(실제 DB 테스트)
|
||||
self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by"}) # 받는 사람 목록·확인 현황 없음
|
||||
self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 200)
|
||||
self.assertEqual(self.client.post("/notice/api/2/ack").status_code, 404) # 받는 사람 아님
|
||||
self.assertEqual(self.client.post("/notice/api/99/ack").status_code, 404)
|
||||
self.assertEqual(self.st.acked, [(1, "bob@test.local")])
|
||||
|
||||
def test_image_access(self):
|
||||
with self.as_(BOB):
|
||||
self.assertEqual(self.client.get("/notice/images/5").status_code, 404) # 받는 사람이 아닌 공지
|
||||
self.assertEqual(self.client.get("/notice/images/6").status_code, 404) # 아직 띄울 시각 전
|
||||
with self.as_({"email": "carol@test.local"}):
|
||||
r = self.client.get("/notice/images/5")
|
||||
self.assertEqual((r.status_code, r.headers["content-type"], r.headers["x-content-type-options"]), (200, "image/png", "nosniff"))
|
||||
with self.as_(SUPER):
|
||||
self.assertEqual(self.client.get("/notice/images/6").status_code, 200)
|
||||
|
||||
def test_not_configured_is_503(self):
|
||||
self.client.app.state.notice_store = None
|
||||
with self.as_(BOB):
|
||||
self.assertEqual(self.client.get("/notice/api/pending").status_code, 503)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,87 @@
|
||||
"""긴급 공지 저장소 — 실제 PostgreSQL(로컬 테스트 DB 전용, PROJECT_TEST_DB_URL 이 localhost 일 때만).
|
||||
|
||||
PROJECT_TEST_DB_URL=postgresql://postgres@127.0.0.1:55432/project_db python -m pytest tests/test_notice_db.py
|
||||
project_db init + 마이그레이션(024 포함)이 적용돼 있어야 한다. 가상의 사용자·공지만 만든다.
|
||||
"""
|
||||
import os
|
||||
import unittest
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.timezone import KST
|
||||
|
||||
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
|
||||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"1" * 32
|
||||
|
||||
|
||||
@unittest.skipUnless(ENABLED, "PROJECT_TEST_DB_URL(localhost) not set")
|
||||
class NoticeDbTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
from app.modules.notice.db import NoticeStore
|
||||
from app.modules.project.db import ProjectStore
|
||||
|
||||
cls.ps = ProjectStore(DSN)
|
||||
cls.st = NoticeStore(cls.ps.pool)
|
||||
cls.tag = uuid.uuid4().hex[:6]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.ps.close()
|
||||
|
||||
def em(self, name):
|
||||
return f"{name}-{self.tag}@test.local"
|
||||
|
||||
def ids(self, email, now=None):
|
||||
return [n["id"] for n in self.st.pending_for(email=email, now=now)]
|
||||
|
||||
def test_schedule_targets_ack_cancel_reshow(self):
|
||||
boss, a, b = self.em("boss"), self.em("a"), self.em("b")
|
||||
now = datetime.now(KST)
|
||||
allp = self.st.create_notice(title="전체", body="<p>x</p>", show_at="", to_all=True, targets=[], by=boss)
|
||||
some = self.st.create_notice(title="a 만", body="", show_at="", to_all=False, targets=[a], by=boss)
|
||||
later = self.st.create_notice(title="예약", body="", show_at=(now + timedelta(hours=2)).isoformat(),
|
||||
to_all=True, targets=[], by=boss)
|
||||
self.assertIn(allp["id"], self.ids(a))
|
||||
self.assertIn(some["id"], self.ids(a))
|
||||
self.assertNotIn(some["id"], self.ids(b)) # 고른 사람만
|
||||
self.assertNotIn(later["id"], self.ids(a)) # 띄울 시각 전
|
||||
self.assertIn(later["id"], self.ids(a, now=now + timedelta(hours=3)))
|
||||
self.assertTrue(self.st.ack(notice_id=allp["id"], email=a))
|
||||
self.assertFalse(self.st.ack(notice_id=allp["id"], email=a)) # 두 번 눌러도 한 번
|
||||
self.assertNotIn(allp["id"], self.ids(a))
|
||||
self.assertIn(allp["id"], self.ids(b))
|
||||
self.st.cancel_notice(notice_id=allp["id"], by=boss)
|
||||
self.assertNotIn(allp["id"], self.ids(b)) # 취소 = 아무에게도 안 뜸
|
||||
self.st.cancel_notice(notice_id=allp["id"], by=boss, cancel=False)
|
||||
self.assertIn(allp["id"], self.ids(b))
|
||||
row = next(n for n in self.st.list_notices() if n["id"] == allp["id"])
|
||||
self.assertEqual(list(row["acks"]), [a])
|
||||
# 고치기 — 받는 사람 바꾸기, reshow 면 확인한 사람에게도 다시
|
||||
self.st.update_notice(notice_id=allp["id"], title="전체(수정)", body="", show_at="", to_all=True, targets=[], by=boss)
|
||||
self.assertNotIn(allp["id"], self.ids(a))
|
||||
self.st.update_notice(notice_id=allp["id"], title="전체(다시)", body="", show_at="", to_all=True, targets=[], by=boss, reshow=True)
|
||||
self.assertIn(allp["id"], self.ids(a))
|
||||
self.st.update_notice(notice_id=some["id"], title="b 로", body="", show_at="", to_all=False, targets=[b], by=boss)
|
||||
self.assertNotIn(some["id"], self.ids(a))
|
||||
self.assertIn(some["id"], self.ids(b))
|
||||
with self.assertRaises(KeyError):
|
||||
self.st.update_notice(notice_id=10 ** 12, title="x", body="", show_at="", to_all=True, targets=[], by=boss)
|
||||
|
||||
def test_images_link_only_own_uploads(self):
|
||||
boss, other = self.em("boss"), self.em("other")
|
||||
mine = self.st.add_image(data=PNG, filename="a.png", by=boss)
|
||||
theirs = self.st.add_image(data=PNG, filename="b.png", by=other)
|
||||
body = f'<p>그림</p><img src="{mine["url"]}"><img src="{theirs["url"]}">'
|
||||
n = self.st.create_notice(title="그림", body=body, show_at="", to_all=True, targets=[], by=boss)
|
||||
self.assertEqual(self.st.get_image(image_id=mine["id"])["notice_id"], n["id"])
|
||||
self.assertIsNone(self.st.get_image(image_id=theirs["id"])["notice_id"]) # 남이 올린 이미지는 묶이지 않는다
|
||||
self.assertEqual(bytes(self.st.get_image(image_id=mine["id"])["data"]), PNG)
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.add_image(data=b"<svg/>", filename="x.svg", by=boss)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -32,6 +32,10 @@ class LockConnection(Connection):
|
||||
if params[0] not in self.meetings:
|
||||
return Result([])
|
||||
return Result([{"completed_at": "done" if params[0] in self.completed else None}])
|
||||
if sql.startswith("SELECT id, week_start") and "FROM goal_meeting_items" in sql and "ORDER BY sort_order" in sql:
|
||||
self.calls.append((sql, params)) # 실제 쿼리처럼 sort_order 순으로(기본 모형은 ORDER BY 를 무시한다)
|
||||
return Result(dict(r) for r in sorted(self.rows.values(), key=lambda r: (r["sort_order"], r["id"]))
|
||||
if r["week_start"] == params[0])
|
||||
if sql.startswith("UPDATE goal_meetings SET"):
|
||||
assert self.locked and self.depth > 0, "머리 변경은 회의록 행을 잠근 트랜잭션 안에서"
|
||||
self.calls.append((sql, params))
|
||||
@@ -95,6 +99,38 @@ class MeetingLockTests(unittest.TestCase):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "잠김"})
|
||||
self.assertEqual(sum(1 for s, _ in self.conn.calls if s.startswith("UPDATE goal_meetings SET")), 1)
|
||||
|
||||
def order(self):
|
||||
return [r["id"] for r in sorted(self.conn.rows.values(), key=lambda r: r["sort_order"])]
|
||||
|
||||
def test_move_section_swaps_whole_blocks(self):
|
||||
# 1·2·3 = 상품, 4 = 유통 → 유통을 위로 = 4,1,2,3 (상품 안 순서·병합은 그대로 따라감)
|
||||
self.conn.rows[1]["content_row_span"] = 2
|
||||
self.st.move_meeting_section(item_id=4, direction=-1)
|
||||
self.assertEqual(self.order(), [4, 1, 2, 3])
|
||||
self.assertEqual(self.conn.rows[1]["content_row_span"], 2)
|
||||
self.st.move_meeting_section(item_id=4, direction=-1) # 맨 위 — 그대로
|
||||
self.assertEqual(self.order(), [4, 1, 2, 3])
|
||||
self.st.move_meeting_section(item_id=2, direction=1) # 상품(이제 맨 아래)의 아무 줄로 아래로 — 그대로
|
||||
self.assertEqual(self.order(), [4, 1, 2, 3])
|
||||
self.st.move_meeting_section(item_id=4, direction=1)
|
||||
self.assertEqual(self.order(), [1, 2, 3, 4])
|
||||
|
||||
def test_move_section_locked_after_completion(self):
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.move_meeting_section(item_id=4, direction=-1)
|
||||
|
||||
def test_move_section_api(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
client = TestClient(app)
|
||||
with patch.object(api, "_require_user", return_value=dict(role="user", email="member@test.local")):
|
||||
self.assertEqual(client.post("/project/api/goals/meeting-items/4/move-section", json={"direction": 0}).status_code, 400)
|
||||
self.assertEqual(client.post("/project/api/goals/meeting-items/4/move-section", json={"direction": -1}).status_code, 200)
|
||||
self.assertEqual(self.order(), [4, 1, 2, 3])
|
||||
self.assertEqual(client.post("/project/api/goals/meeting-items/99/move-section", json={"direction": 1}).status_code, 404)
|
||||
|
||||
def test_anyone_edits_but_only_admin_completes(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
|
||||
@@ -1166,6 +1166,197 @@ def test_review_meeting_result_lock_rules():
|
||||
_drop_meetings([w1, w2])
|
||||
|
||||
|
||||
def test_review_meeting_section_move():
|
||||
"""구역(첫 열) 통째로 위/아래 — 묶음 안 줄 순서 그대로, 다음 주 회의록이 바뀐 순서를 이어받는다."""
|
||||
from app.modules.project import store
|
||||
|
||||
w1 = store.month_weeks(2031, 11)[1][0] # 11월 2주차 시작일(주차 시작일이어야 회의록을 만든다)
|
||||
w2 = store.week_period(w1)[1] + timedelta(days=1)
|
||||
_drop_meetings([w1, w2])
|
||||
try:
|
||||
_create_meeting(w1)
|
||||
secs = lambda w: [s for i, s in enumerate(r["section"] for r in ST.get_meeting(week_start=w)["items"])
|
||||
if i == 0 or s != ST.get_meeting(week_start=w)["items"][i - 1]["section"]]
|
||||
before = secs(w1)
|
||||
assert len(before) >= 2, before
|
||||
items = ST.get_meeting(week_start=w1)["items"]
|
||||
second = next(r for r in items if r["section"] == before[1])
|
||||
labels_second = [r["label"] for r in items if r["section"] == before[1]]
|
||||
r = req("POST", f"/project/api/goals/meeting-items/{second['id']}/move-section", BOB, json={"direction": -1})
|
||||
assert r.status_code == 200, r.text
|
||||
after = secs(w1)
|
||||
assert after[:2] == [before[1], before[0]] and after[2:] == before[2:], (before, after)
|
||||
assert [r["label"] for r in ST.get_meeting(week_start=w1)["items"] if r["section"] == before[1]] == labels_second
|
||||
_create_meeting(w2)
|
||||
assert secs(w2) == after # 다음 회의록은 바뀐 구역 순서를 이어받는다
|
||||
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
|
||||
assert req("POST", f"/project/api/goals/meeting-items/{second['id']}/move-section", BOB,
|
||||
json={"direction": 1}).status_code == 409 # 회의 완료 뒤 잠금
|
||||
finally:
|
||||
_drop_meetings([w1, w2])
|
||||
|
||||
|
||||
def test_review_meeting_label_groups():
|
||||
"""항목 칸 묶음(027) — 주요 업무 칸에서 추가(same_label)는 같은 항목 칸 안에(아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이
|
||||
첫 줄·이름 넘겨받음), 화면은 항목 칸 rowspan, 묶인 줄은 순서 이동 거절, 다음 주 회의록이 묶음을 이어받음,
|
||||
첫 줄 삭제 = 아래 줄이 이름을 이어받음, 항목 칸 나누기, 회의 완료 뒤 잠금."""
|
||||
from app.modules.project import store
|
||||
|
||||
w1 = store.month_weeks(2032, 2)[1][0]
|
||||
w2 = store.week_period(w1)[1] + timedelta(days=1)
|
||||
_drop_meetings([w1, w2])
|
||||
try:
|
||||
_create_meeting(w1)
|
||||
rows = lambda w=w1: ST.get_meeting(week_start=w)["items"] # noqa: E731
|
||||
a = rows()[0]
|
||||
url = f"/project/api/goals/meetings/{w1}/items"
|
||||
r = req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "below", "same_label": True})
|
||||
assert r.status_code == 201, r.text
|
||||
b_id = r.json()["id"]
|
||||
cur = rows()
|
||||
k = [x["id"] for x in cur].index(a["id"])
|
||||
assert cur[k + 1]["id"] == b_id and cur[k + 1]["label_cont"] and cur[k + 1]["label"] == "" and not cur[k]["label_cont"]
|
||||
# 묶음 첫 줄 위 → 새 줄이 첫 줄(이름 넘겨받음), 기준 줄은 이어 붙음
|
||||
r = req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "above", "same_label": True})
|
||||
assert r.status_code == 201, r.text
|
||||
c_id = r.json()["id"]
|
||||
cur = rows()
|
||||
ids = [x["id"] for x in cur]
|
||||
k = ids.index(c_id)
|
||||
assert ids[k:k + 3] == [c_id, a["id"], b_id], ids
|
||||
assert cur[k]["label"] == a["label"] and not cur[k]["label_cont"]
|
||||
assert cur[k + 1]["label"] == "" and cur[k + 1]["label_cont"] and cur[k + 2]["label_cont"]
|
||||
# 줄마다 연결키는 따로(지난주 리뷰가 줄 단위로 이어짐)
|
||||
assert len({cur[k + n]["line_key"] for n in range(3)}) == 3
|
||||
# 화면 — 회의록 화면이 그려지고(이 테스트 환경은 템플릿을 실제로 그리지 않음 — 표 모양은 jsdom [2h]),
|
||||
# 화면용 묶음 계산(라우터 도우미) = 항목 칸 rowspan 3 · 이어 붙은 줄은 항목 칸 없음
|
||||
from app.modules.project.router import _meeting_label_spans
|
||||
page = req("GET", f"/project/goals/{w1.year}/meetings/{w1.month}?week={w1}&content=1", BOB)
|
||||
assert page.status_code == 200, page.text[:300]
|
||||
sec_rows = [x for x in rows() if x["section"] == a["section"]]
|
||||
_meeting_label_spans(sec_rows)
|
||||
spans = {x["id"]: (x.get("label_span"), x["label_hidden"], x["label_shown"]) for x in sec_rows}
|
||||
assert spans[c_id][:2] == (3, False) and spans[a["id"]][1] and spans[b_id][1], spans
|
||||
assert spans[b_id][2] == a["label"]
|
||||
# 묶인 줄은 옮길 수 없다(항목 칸을 나눈 뒤)
|
||||
r = req("POST", f"/project/api/goals/meeting-items/{a['id']}/move", BOB, json={"direction": 1})
|
||||
assert r.status_code == 400 and "항목 칸" in r.text, r.text
|
||||
# 같은 항목 칸 추가는 기준 줄이 필요
|
||||
assert req("POST", url, BOB, json={"section": a["section"], "same_label": True}).status_code == 400
|
||||
# 다음 주 회의록 — 묶음을 그대로 이어받음(연결키 기준)
|
||||
_create_meeting(w2)
|
||||
by_key = {x["line_key"]: x for x in rows(w2)}
|
||||
assert [bool(by_key[cur[k + n]["line_key"]]["label_cont"]) for n in range(3)] == [False, True, True]
|
||||
assert by_key[cur[k]["line_key"]]["label"] == a["label"]
|
||||
# 첫 줄(c) 삭제 → 바로 아래 줄(a)이 첫 줄이 되고 이름을 이어받음
|
||||
assert req("DELETE", f"/project/api/goals/meeting-items/{c_id}", BOB).status_code == 200
|
||||
cur = rows()
|
||||
k = [x["id"] for x in cur].index(a["id"])
|
||||
assert not cur[k]["label_cont"] and cur[k]["label"] == a["label"] and cur[k + 1]["id"] == b_id and cur[k + 1]["label_cont"]
|
||||
# 항목 칸 나누기 → b 가 따로(이름 빈 칸)
|
||||
r = req("POST", f"/project/api/goals/meeting-items/{a['id']}/split-label", BOB)
|
||||
assert r.status_code == 200 and r.json()["split"] == 1, r.text
|
||||
cur = rows()
|
||||
k = [x["id"] for x in cur].index(b_id)
|
||||
assert not cur[k]["label_cont"] and cur[k]["label"] == ""
|
||||
assert req("POST", f"/project/api/goals/meeting-items/{a['id']}/move", BOB, json={"direction": 1}).status_code == 200
|
||||
# 회의 완료 뒤 잠금
|
||||
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
|
||||
assert req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "below",
|
||||
"same_label": True}).status_code == 409
|
||||
finally:
|
||||
_drop_meetings([w1, w2])
|
||||
|
||||
|
||||
def _clear_quick(*weeks) -> None:
|
||||
"""작업 등록 표 테스트 주차 비우기(로컬 테스트 DB — 앞선 실패한 실행의 줄이 남지 않게)."""
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
conn.execute("DELETE FROM goal_meeting_tasks WHERE week_start = ANY(%s)", (list(weeks),))
|
||||
|
||||
|
||||
def test_review_meeting_quick_tasks_shared():
|
||||
"""작업 등록 표(025) — 주차별 한 표를 모두가 같이 본다. 남의 프로젝트 이름은 가리고, [적용]은 동시에 눌러도 작업 하나."""
|
||||
from app.modules.project import store
|
||||
|
||||
w = store.month_weeks(2031, 12)[1][0]
|
||||
other = store.month_weeks(2031, 12)[2][0]
|
||||
_clear_quick(w, other)
|
||||
p = _project("P-quick", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
done = _stage(p["id"], name="완료", done=True, by=ADMIN)
|
||||
url = f"/project/api/goals/meetings/{w}/quick-tasks"
|
||||
r = req("POST", url, BOB, json={"title": "상세페이지 수정", "project_id": p["id"], "stage_id": s["id"], "assignee_email": BOB})
|
||||
assert r.status_code == 201, r.text
|
||||
row = r.json()["task"]
|
||||
# 다른 사람(ALICE — 이 프로젝트 멤버 아님)도 같은 표를 본다 — 프로젝트 이름은 가림
|
||||
seen = req("GET", url, ALICE).json()["tasks"]
|
||||
assert [x["id"] for x in seen] == [row["id"]] and seen[0]["title"] == "상세페이지 수정"
|
||||
assert seen[0]["visible"] is False and seen[0]["project_name"] == "(볼 수 없는 프로젝트)"
|
||||
assert req("GET", f"/project/api/goals/meetings/{other}/quick-tasks", BOB).json()["tasks"] == [] # 주차마다 따로
|
||||
# 남의 프로젝트는 고를 수 없다
|
||||
assert req("POST", url, ALICE, json={"title": "x", "project_id": p["id"]}).status_code == 403
|
||||
# 고치기 — 다른 프로젝트 섹션은 거절, 제목은 저장
|
||||
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"stage_id": 10 ** 9}).status_code == 400
|
||||
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"title": "상세페이지 수정2"}).status_code == 200
|
||||
# [적용] — 비멤버는 403, 멤버가 동시에 4번 눌러도 작업 하나
|
||||
assert req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", ALICE).status_code == 403
|
||||
outs = _race([lambda: req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", BOB) for _ in range(4)])
|
||||
assert sorted(o.status_code for o in outs) == [200, 200, 200, 201], [o.status_code for o in outs]
|
||||
tid = next(o.json()["task"]["task_id"] for o in outs if o.status_code == 201)
|
||||
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE project_id = %s AND title = %s", p["id"], "상세페이지 수정2") == 1
|
||||
t = ST.get_task(task_id=tid)
|
||||
assert t["stage_id"] == s["id"] and t["assignee_email"] == BOB
|
||||
# 등록된 줄은 더 못 고침(409), 다시 [적용]해도 그대로
|
||||
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"title": "x"}).status_code == 409
|
||||
# 작업 칸 — 방금 만든 작업을 고르면 그 작업의 세부 작업으로(섹션 없음)
|
||||
r = req("POST", url, BOB, json={"title": "세부 하나", "project_id": p["id"], "parent_task_id": tid})
|
||||
sub = r.json()["task"]
|
||||
assert sub["parent_task_id"] == tid and sub["parent_task_title"] == "상세페이지 수정2"
|
||||
r = req("POST", f"/project/api/goals/meeting-quick-tasks/{sub['id']}/apply", BOB)
|
||||
assert r.status_code == 201, r.text
|
||||
st_ = ST.get_task(task_id=r.json()["task"]["task_id"])
|
||||
assert st_["parent_task_id"] == tid and st_["stage_id"] is None
|
||||
# 회의 완료면 잠금
|
||||
_drop_meetings([w])
|
||||
try:
|
||||
_create_meeting(w)
|
||||
ST.set_meeting_completed(week_start=w, done=True, by=ADMIN)
|
||||
assert req("POST", url, BOB, json={"title": "늦게"}).status_code == 409
|
||||
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{sub['id']}", BOB).status_code == 409
|
||||
finally:
|
||||
_drop_meetings([w])
|
||||
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB).status_code == 200
|
||||
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{sub['id']}", BOB).status_code == 200
|
||||
assert req("GET", url, BOB).json()["tasks"] == []
|
||||
_ = done
|
||||
|
||||
|
||||
def test_review_meeting_quick_parent_task_column():
|
||||
"""작업 칸(026) — 그 프로젝트의 작업만, 프로젝트를 바꾸면 비움, 고른 작업이 사라지면 [적용] 400."""
|
||||
from app.modules.project import store
|
||||
|
||||
w = store.month_weeks(2032, 1)[1][0]
|
||||
_clear_quick(w)
|
||||
p = _project("P-quick-pt", ADMIN, (BOB,))
|
||||
q = _project("P-quick-pt2", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
base = ST.create_task(project_id=p["id"], title="기존 작업", stage_id=s["id"], created_by=ADMIN)
|
||||
other = ST.create_task(project_id=q["id"], title="다른 프로젝트 작업", created_by=ADMIN)
|
||||
url = f"/project/api/goals/meetings/{w}/quick-tasks"
|
||||
put = lambda i, body: req("PUT", f"/project/api/goals/meeting-quick-tasks/{i}", BOB, json=body)
|
||||
assert req("POST", url, BOB, json={"title": "x", "project_id": p["id"], "parent_task_id": other["id"]}).status_code == 400
|
||||
row = req("POST", url, BOB, json={"title": "세부", "project_id": p["id"], "parent_task_id": base["id"]}).json()["task"]
|
||||
assert row["parent_task_id"] == base["id"]
|
||||
moved = put(row["id"], {"project_id": q["id"]}).json()["task"]
|
||||
assert moved["parent_task_id"] is None and moved["stage_id"] is None # 프로젝트가 바뀌면 작업·섹션을 비움
|
||||
assert put(row["id"], {"project_id": p["id"], "parent_task_id": base["id"]}).json()["task"]["parent_task_id"] == base["id"]
|
||||
# 고른 작업이 지워지면 [적용]은 400(줄은 그대로)
|
||||
ST.delete_task(task_id=base["id"], deleted_by=ADMIN)
|
||||
assert req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", BOB).status_code == 400
|
||||
assert req("GET", url, BOB).json()["tasks"][0]["task_id"] is None
|
||||
req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
|
||||
Reference in New Issue
Block a user