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>
This commit is contained in:
2026-10-12 14:07:10 +09:00
parent 1759e00213
commit 2aa6b6efae
22 changed files with 1489 additions and 2 deletions
+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
+183
View File
@@ -0,0 +1,183 @@
"""긴급 공지 라우터(/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()
people = sorted(
({"email": u["email"], "name": u.get("name") or u["email"].split("@")[0]} for u in user_store.list_all()),
key=lambda p: p["email"],
)
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,63 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% 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">내용
<div class="ntc-editor-bar">
<button type="button" data-cmd="bold" title="굵게"><b>B</b></button>
<button type="button" id="ntc-image-btn" title="이미지 넣기(붙여넣기·끌어 놓기도 됩니다)">이미지</button>
<input type="file" id="ntc-image-file" accept="image/png,image/jpeg,image/gif,image/webp" hidden multiple />
</div>
<div class="ntc-editor" id="ntc-body" contenteditable="true" role="textbox" aria-multiline="true" aria-label="공지 내용"
data-placeholder="공지 내용을 쓰세요. 이미지는 붙여넣거나 끌어 놓아도 됩니다."></div>
</div>
<label class="ntc-field">띄울 시각(한국시간 — 비우면 바로)
<input type="datetime-local" id="ntc-show-at" />
</label>
<div class="ntc-field">받는 사람
<div class="ntc-targets">
<label><input type="radio" name="ntc-to" value="all" checked /> 전체(로그인하는 모든 사람)</label>
<label><input type="radio" name="ntc-to" value="some" /> 고른 사람만</label>
<div class="ntc-people" id="ntc-people" hidden>
{% for p in people %}
<label><input type="checkbox" value="{{ p.email }}" /> {{ p.name }} <small>{{ p.email.split('@')[0] }}</small></label>
{% endfor %}
</div>
</div>
</div>
<label class="ntc-field" id="ntc-reshow-row" hidden style="flex-direction:row;align-items:center;font-weight:500">
<input type="checkbox" id="ntc-reshow" /> 이미 [확인]한 사람에게도 다시 띄우기
</label>
<div class="ntc-actions">
<button type="button" class="erp-btn erp-btn-outline" id="ntc-reset">새로 쓰기</button>
<button type="button" class="erp-btn erp-btn-outline" id="ntc-preview">미리 보기</button>
<button type="button" class="erp-btn" 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/erp-notice-admin.js?v=20261012a" defer></script>
{% endif %}
{% endblock %}
+5
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
# ════════════════════════════════════════════════════════════
# 프로젝트 / 서브프로젝트
# ════════════════════════════════════════════════════════════
@@ -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>
+221
View File
@@ -0,0 +1,221 @@
// 긴급 공지 관리(/notice/, 수퍼관리자) — 만들기·고치기·취소·이미지·미리 보기·확인 현황.
(function () {
"use strict";
const root = document.getElementById("ntc-root");
if (!root) return;
const $ = function (id) { return document.getElementById(id); };
const people = {};
(window.NTC_PEOPLE || []).forEach(function (p) { people[String(p.email).toLowerCase()] = p.name; });
const nameOf = function (e) { return people[String(e).toLowerCase()] || 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"), body = $("ntc-body"), showAt = $("ntc-show-at"), 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.style.color = ok ? "#1f7a3a" : ""; };
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(); });
});
// ── 본문 편집 — 굵게, 이미지(버튼·붙여넣기·끌어 놓기 → 서버에 올리고 주소로 넣는다) ──
root.querySelector('[data-cmd="bold"]').addEventListener("click", function () { body.focus(); document.execCommand("bold"); });
let savedRange = null;
body.addEventListener("keyup", keepRange);
body.addEventListener("mouseup", keepRange);
body.addEventListener("blur", keepRange);
function keepRange() {
const s = window.getSelection();
if (s.rangeCount && body.contains(s.getRangeAt(0).commonAncestorContainer)) savedRange = s.getRangeAt(0).cloneRange();
}
function insertNode(node) {
body.focus();
const s = window.getSelection();
let r = savedRange && body.contains(savedRange.commonAncestorContainer) ? savedRange : null;
if (!r) { r = document.createRange(); r.selectNodeContents(body); r.collapse(false); }
r.deleteContents();
r.insertNode(node);
r.setStartAfter(node); r.collapse(true);
s.removeAllRanges(); s.addRange(r);
savedRange = r.cloneRange();
}
let uploading = 0;
async function uploadImages(files) {
for (const f of files) {
if (!/^image\/(png|jpeg|gif|webp)$/.test(f.type)) { say("이미지(png·jpg·gif·webp)만 넣을 수 있습니다: " + f.name); continue; }
uploading++;
save.disabled = true;
try {
const fd = new FormData();
fd.append("file", f, f.name || "image");
const res = await api("POST", "/notice/api/images", fd, true);
const img = document.createElement("img");
img.src = res.image.url;
img.alt = f.name || "";
insertNode(img);
say("");
} catch (e) { say("이미지를 올리지 못했습니다: " + e.message); }
finally { uploading--; if (!uploading) save.disabled = false; }
}
}
$("ntc-image-btn").addEventListener("click", function () { keepRange(); $("ntc-image-file").click(); });
$("ntc-image-file").addEventListener("change", function (e) { uploadImages(Array.from(e.target.files || [])); e.target.value = ""; });
body.addEventListener("paste", function (e) {
const files = Array.from((e.clipboardData && e.clipboardData.files) || []).filter(function (f) { return /^image\//.test(f.type); });
if (files.length) { e.preventDefault(); keepRange(); uploadImages(files); }
});
body.addEventListener("dragover", function (e) { e.preventDefault(); });
body.addEventListener("drop", function (e) {
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []).filter(function (f) { return /^image\//.test(f.type); });
if (files.length) { e.preventDefault(); keepRange(); uploadImages(files); }
});
// ── 저장(만들기·고치기) ──
function payload() {
return {
title: title.value.trim(), body_html: body.innerHTML, show_at: showAt.value || "",
to_all: toAll(),
targets: Array.from(peopleBox.querySelectorAll("input:checked")).map(function (c) { return c.value; }),
reshow: $("ntc-reshow").checked,
};
}
function resetForm() {
idEl.value = ""; title.value = ""; body.innerHTML = ""; showAt.value = "";
root.querySelector('input[name="ntc-to"][value="all"]').checked = true;
peopleBox.hidden = true;
peopleBox.querySelectorAll("input").forEach(function (c) { c.checked = false; });
$("ntc-reshow").checked = false; $("ntc-reshow-row").hidden = true;
$("ntc-form-title").textContent = "새 긴급 공지";
save.textContent = "공지 만들기";
savedRange = null;
}
$("ntc-reset").addEventListener("click", function () { resetForm(); say(""); });
let saving = false;
save.addEventListener("click", async function () {
if (saving || uploading) return;
const p = payload();
if (!p.title) { say("제목을 입력하세요."); title.focus(); return; }
if (!p.to_all && !p.targets.length) { say("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요."); return; }
saving = true; save.disabled = true;
try {
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() || "(제목 없음)", body.innerHTML); });
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="erp-btn erp-btn-outline" data-act="preview">미리 보기</button>' +
'<button type="button" class="erp-btn erp-btn-outline" data-act="edit">고치기</button>' +
'<button type="button" class="erp-btn erp-btn-outline" 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; body.innerHTML = n.body_html; showAt.value = (n.show_at || "").slice(0, 16);
root.querySelector('input[name="ntc-to"][value="' + (n.to_all ? "all" : "some") + '"]').checked = true;
peopleBox.hidden = n.to_all;
peopleBox.querySelectorAll("input").forEach(function (c) { c.checked = n.targets.indexOf(c.value.toLowerCase()) >= 0; });
$("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();
})();
+82
View File
@@ -0,0 +1,82 @@
/* 긴급 공지 — 화면 가로·세로 정가운데(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; }
.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(360px, 520px) 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-field input[type=datetime-local] {
font: inherit; font-weight: 500; padding: 8px 10px; border: 1px solid #d5d9de; border-radius: 8px;
}
.ntc-editor-bar { display: flex; gap: 4px; }
.ntc-editor-bar button { padding: 4px 10px; border: 1px solid #d5d9de; border-radius: 6px; background: #fff; cursor: pointer; font: inherit; font-size: 12.5px; }
.ntc-editor {
min-height: 160px; max-height: 420px; overflow: auto; padding: 10px 12px; border: 1px solid #d5d9de; border-radius: 8px;
font-weight: 400; font-size: 14px; line-height: 1.6; color: #2b2f36; outline: none;
}
.ntc-editor:focus { border-color: #7b68ee; box-shadow: 0 0 0 3px rgba(123, 104, 238, .15); }
.ntc-editor:empty::before { content: attr(data-placeholder); color: #a0a5ad; }
.ntc-editor img { max-width: 100%; height: auto; border-radius: 6px; }
.ntc-targets { display: flex; flex-direction: column; gap: 6px; font-weight: 500; }
.ntc-people { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 4px 10px; max-height: 220px; overflow: auto;
padding: 8px; border: 1px solid #e6e8eb; border-radius: 8px; }
.ntc-people[hidden] { display: none; }
.ntc-people label { display: flex; align-items: center; gap: 6px; font-size: 13px; 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-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();
})();
+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=20261012a" />
<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=20261012a" />
{% 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=20261012a" />
<script src="/static/erp-notice.js?v=20261012a" defer></script>
</body>
</html>