9 Commits

Author SHA1 Message Date
king 3a9a94f97b Merge branch 'feat/notice-project-parts' 2026-10-12 14:44:38 +09:00
king c69bc0e9f3 feat(notice): reuse project editor, date popup and member picker on the notice page
- Notice body uses the task description editor (createDescEditor, shared toolbar partial
  project/_desc_fmtbar.html): bold/italic/underline/strike, text color/size, lists, checklist,
  quote, link, clear format, image button/paste with resize; images upload to /notice/api/images
- Show date uses the project date popup (enhanceDateInput) plus a time field
- Recipients rendered like the project member picker (icon + name + check)
- project.js exposes window.PJLib; PJ_LIB_ONLY runs only shared tooltips on non-project pages
- Centered notice renders checklist/quote/list styles outside project pages too
- Task window editor behavior unchanged (jsdom + Chrome regressions pass)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:44:33 +09:00
king 833dbb5fdf Merge branch 'feat/urgent-notice' 2026-10-12 14:07:15 +09:00
king 2aa6b6efae feat(notice): urgent notices centered on every ERP screen until acknowledged
- Super admin only: /notice/ page (title, body with images, show time KST, all or picked people,
  preview, edit with optional re-show, cancel/undo, per-person acknowledgement status)
- Shown on every ERP page (erp_base, main, admin) dead center; [확인] only (no Esc/backdrop close),
  queue in order, ack failure keeps the dialog, closes when acked/cancelled elsewhere
- project_db migration 024 (urgent_notices, targets, acks, images as bytea); shares ProjectStore.pool
- Body sanitized like task descriptions, images restricted to /notice/images/{id}, type sniffed
- Entry points: ERP sidebar foot and Project options dialog (super admin)
- Docs (NOTICE_MODULE, DEPLOYMENT 024, overview, CLAUDE.md); tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:07:10 +09:00
king 1759e00213 Merge branch 'feat/meeting-tips-quick-create' 2026-10-12 13:52:38 +09:00
king fa6e7066ae feat(project): tooltips stay above the cursor; create project/section from meeting task table
- Hover tips: keep above the cursor even near the top edge (tighter tail gap); flip below only
  when there is no room, 28px under the cursor so the pointer never covers the text
- Meeting task table: "new project" (Pro user+) and "new section" at the top of the pickers,
  created by name and selected right away
- Help + docs; jsdom tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:52:34 +09:00
king 7cdca852bd Merge branch 'feat/meeting-section-move' 2026-10-12 13:29:58 +09:00
king ee09e8bfd1 feat(project): move whole meeting sections up/down from the 구분 column
- 구분 cell: right-click or ⋯ menu → 구역 위로 / 구역 아래로 / 구역 끝에 줄 추가
- POST /api/goals/meeting-items/{id}/move-section swaps the contiguous section block
  with its neighbour under the meeting lock (row order and merges follow; 409 after completion)
- Next meetings inherit the new order; help + docs; tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:29:53 +09:00
king ae6b6ec603 Merge branch 'feat/project-review-fixes-1012' 2026-10-12 13:23:18 +09:00
38 changed files with 1851 additions and 78 deletions
+3 -1
View File
File diff suppressed because one or more lines are too long
+6
View File
@@ -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:
+23
View File
@@ -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)
+208
View File
@@ -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
+185
View File
@@ -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)
+106
View File
@@ -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=20261012b" />
<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=20261012e" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %}
{% endblock %}
+28
View File
@@ -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
# ════════════════════════════════════════════════════════════
# 프로젝트 / 서브프로젝트
# ════════════════════════════════════════════════════════════
@@ -3320,6 +3325,29 @@ class ProjectStore:
for n, x in enumerate(ids):
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
def move_meeting_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 goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
with self._pool.connection() as conn:
+16
View File
@@ -3737,3 +3737,19 @@ 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}/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})
@@ -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=20261012b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -227,7 +227,8 @@
<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 %}>
{% 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">
@@ -291,5 +292,5 @@
<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.js?v=20261012e" 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=20261012b" />
<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=20261012e" 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=20261012b" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -636,7 +636,7 @@
<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> — 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다. 목록 맨 위 <span class="pjh-ui">새 프로젝트</span>(Pro user 이상)·<span class="pjh-ui">새 섹션</span>(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 <span class="pjh-ui">새 섹션</span>을 만들어 고르세요.</li>
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 <b>등록됨</b> 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 작업도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 작업 삭제는 만든 사람만 할 수 있습니다.</li>
@@ -697,6 +697,7 @@
<ul>
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
<li><b>구역 순서</b> — 첫 열 <b>구분</b> 칸을 우클릭하거나 마우스를 올려 나오는 <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=20261012b" />
<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=20261012e" 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=20261012b" />
<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=20261012e" 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=20261012b" />
<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=20261012e" 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=20261012b" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — 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=20261012e" 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=20261012b" />
<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=20261012e" defer></script>
{% endblock %}
+200
View File
@@ -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 { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[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();
})();
+97
View File
@@ -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; }
+118
View File
@@ -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 { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[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();
})();
+2
View File
@@ -2811,6 +2811,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;
+120 -36
View File
@@ -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) {
@@ -10724,23 +10740,41 @@
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.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();
}
// 목록 맨 위 "+ 새 프로젝트" — 새 프로젝트는 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] = [];
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) {
// 프로젝트를 골랐으면 그 프로젝트 멤버·소유자만(작업을 볼 수 있는 사람), 아니면 프로젝트 권한이 있는 전체 직원
@@ -10754,9 +10788,21 @@
async function pickStage(r, btn) {
if (!r.projectId) { showToast("프로젝트를 먼저 고르세요."); return; }
const stages = await stagesOf(r.projectId);
menuAt(btn, stages.map(function (st) {
const pid = r.projectId;
// 목록 맨 위 "+ 새 섹션" — 그 프로젝트 멤버 누구나(서버 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) { r.stageId = res.stage.id; r.stageName = res.stage.name; save(); render(); }
showToast("섹션 ‘" + res.stage.name + "’를 만들었습니다.");
} catch (e) { showToast("섹션 만들기 실패: " + e.message, "error"); }
} }, null];
menuAt(btn, head.concat(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(); } };
}));
})));
}
async function apply(r, btn) {
if (!r.title.trim()) { showToast("작업 제목을 쓰세요."); return; }
@@ -11197,6 +11243,26 @@
} },
].concat(cellGrid ? [null].concat(cellGrid.widthItems(tr.querySelector("th.pj-meet-c-label"))) : []));
}
// ── 구역 메뉴(구분 칸 ⋯ · 우클릭) — 구역을 통째로 위/아래(그 안의 줄 순서·병합은 그대로), 구역 끝에 줄 추가 ──
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]");
if (!b) return;
@@ -11204,13 +11270,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 +11421,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();
+4 -1
View File
@@ -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>
+13
View File
@@ -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>
+4 -1
View File
@@ -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>
+13
View File
@@ -125,6 +125,19 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
## 긴급 공지 마이그레이션 (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` 화면은
+57
View File
@@ -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 멈춤.
+11
View File
@@ -1191,6 +1191,17 @@ 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): 프로젝트 칸 목록 맨 위 "새 프로젝트"(Pro user 이상만 보임 — `POST /api/projects`,
만든 사람이 소유자), 섹션 칸 맨 위 "새 섹션"(그 프로젝트 멤버 — `POST /api/projects/{id}/stages`). 이름만 묻고 만든 뒤 바로 그 칸에 고른다.
- **말풍선 위치**(`initHoverTips`, 2026-10-12): 늘 커서 위 — 위 여유가 적으면(화면 맨 위 회의록 머리 버튼 등) 꼬리 간격을 줄여(커서 8px 위)
위에 두고, 그래도 안 들어갈 때만 아래로 뒤집되 마우스 화살표에 가리지 않게 커서 28px 아래. 예전엔 위 여백이 말풍선 높이+20px 보다
작으면 커서 바로 아래(22px)로 뒤집혀 화살표가 글자를 가렸다.
정책 결정이 필요한 것(바꾸지 않음): 배정·완료 **메일**은 `PROJECT_NOTIFY_EMAIL`(없으면 Admin 전원)에게 프로젝트·작업 제목·담당자가
간다 — 화면에선 비멤버 Admin 이 그 프로젝트를 못 보지만 메일로는 제목을 받는다(4장 관리자 보고 정책).
+1
View File
@@ -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,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;
+71 -1
View File
@@ -352,6 +352,29 @@ function meetServer(env, st) {
{ nav: env.navigations });
});
// 첫 열(구분) — 구역 통째로 위/아래(우클릭·⋯), 맨 위는 "위로" 없음, 구역 첫 줄 id 로 요청
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
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);
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); });
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 === 1, [call, env.navigations]);
const last = blocks[blocks.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);
@@ -518,7 +541,7 @@ 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);
const people = await pickItem("assignee", "Kim");
@@ -541,6 +564,53 @@ function meetServer(env, st) {
check("[2g] 적용 전 줄 × → 줄만 지움", d.querySelectorAll("#pj-meet-quick tbody tr").length === n - 1 && env.calls.length === calls);
}, { notifyOnFail: true });
// ════════════════════ [2g2] 작업 등록 — 프로젝트·섹션 목록 맨 위에서 바로 만들기 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { promptAnswer: "신규 브랜드" });
meetServer(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);
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 === "신규 브랜드", [madeStage, row().textContent]);
});
await section(async function () {
const env = makeEnv(PAGE.meeting_member, MEET_URL);
meetServer(env);
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [{ id: 7, name: "브랜드", parent_id: null }] } }; });
await boot(env);
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);
});
// ════════════════════ [2h] 회의록은 누구나 수정 · [회의 완료](관리자)면 잠금 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_member, MEET_URL);
+73
View File
@@ -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); });
+164
View File
@@ -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()
+87
View File
@@ -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()
+36
View File
@@ -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)
+30
View File
@@ -1166,6 +1166,36 @@ 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])
if __name__ == "__main__":
if not ENABLED:
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")