From 2aa6b6efaef635984738e9f75bfc0a8b8f78b786 Mon Sep 17 00:00:00 2001 From: king Date: Mon, 12 Oct 2026 14:07:10 +0900 Subject: [PATCH] feat(notice): urgent notices centered on every ERP screen until acknowledged MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- CLAUDE.md | 2 + app/main.py | 6 + app/modules/notice/__init__.py | 23 ++ app/modules/notice/db.py | 208 +++++++++++++++++ app/modules/notice/router.py | 183 +++++++++++++++ app/modules/notice/store.py | 106 +++++++++ .../notice/templates/notice/admin.html | 63 +++++ app/modules/project/db.py | 5 + .../project/templates/project/_options.html | 1 + app/static/erp-notice-admin.js | 221 ++++++++++++++++++ app/static/erp-notice.css | 82 +++++++ app/static/erp-notice.js | 118 ++++++++++ app/templates/admin.html | 5 +- app/templates/erp_base.html | 13 ++ app/templates/main.html | 5 +- docs/DEPLOYMENT.md | 13 ++ docs/NOTICE_MODULE.md | 51 ++++ docs/PROJECT_OVERVIEW.md | 1 + scripts/sql/project_db_024_urgent_notices.sql | 61 +++++ tests/js/notice_ui.test.js | 73 ++++++ tests/test_notice.py | 164 +++++++++++++ tests/test_notice_db.py | 87 +++++++ 22 files changed, 1489 insertions(+), 2 deletions(-) create mode 100644 app/modules/notice/__init__.py create mode 100644 app/modules/notice/db.py create mode 100644 app/modules/notice/router.py create mode 100644 app/modules/notice/store.py create mode 100644 app/modules/notice/templates/notice/admin.html create mode 100644 app/static/erp-notice-admin.js create mode 100644 app/static/erp-notice.css create mode 100644 app/static/erp-notice.js create mode 100644 docs/NOTICE_MODULE.md create mode 100644 scripts/sql/project_db_024_urgent_notices.sql create mode 100644 tests/js/notice_ui.test.js create mode 100644 tests/test_notice.py create mode 100644 tests/test_notice_db.py diff --git a/CLAUDE.md b/CLAUDE.md index df2762a..a267364 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,6 +40,8 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md` +- 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md` + 상세는 `docs/PROJECT_OVERVIEW.md`. --- diff --git a/app/main.py b/app/main.py index b2c14e3..2c1c310 100644 --- a/app/main.py +++ b/app/main.py @@ -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: diff --git a/app/modules/notice/__init__.py b/app/modules/notice/__init__.py new file mode 100644 index 0000000..19c3a61 --- /dev/null +++ b/app/modules/notice/__init__.py @@ -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) diff --git a/app/modules/notice/db.py b/app/modules/notice/db.py new file mode 100644 index 0000000..77b62c7 --- /dev/null +++ b/app/modules/notice/db.py @@ -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 + diff --git a/app/modules/notice/router.py b/app/modules/notice/router.py new file mode 100644 index 0000000..86f3058 --- /dev/null +++ b/app/modules/notice/router.py @@ -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) diff --git a/app/modules/notice/store.py b/app/modules/notice/store.py new file mode 100644 index 0000000..7e8a8e0 --- /dev/null +++ b/app/modules/notice/store.py @@ -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"]*>", 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)만 올릴 수 있습니다.") diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html new file mode 100644 index 0000000..9f649cc --- /dev/null +++ b/app/modules/notice/templates/notice/admin.html @@ -0,0 +1,63 @@ +{% extends "erp_base.html" %} + +{% block head_extra %} + +{% endblock %} + +{% block content %} +{% if not enabled %} +
+

긴급 공지 준비 필요

+

project_db 마이그레이션 024(scripts/sql/project_db_024_urgent_notices.sql)를 적용하면 사용할 수 있습니다.

+
+{% else %} +
+
+

새 긴급 공지

+ + +
내용 +
+ + + +
+
+
+ +
받는 사람 +
+ + + +
+
+ +
+ + + +
+ +
+ +
+

공지 목록

+
불러오는 중…
+
+
+ + +{% endif %} +{% endblock %} diff --git a/app/modules/project/db.py b/app/modules/project/db.py index ecc8699..f3d638f 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -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 + # ════════════════════════════════════════════════════════════ # 프로젝트 / 서브프로젝트 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/project/templates/project/_options.html b/app/modules/project/templates/project/_options.html index f66f29b..3155d31 100644 --- a/app/modules/project/templates/project/_options.html +++ b/app/modules/project/templates/project/_options.html @@ -14,6 +14,7 @@
프로젝트와 목표를 한눈에
Project · 업무 이름 · 가나다 123

이 브라우저의 모든 Project 화면에 적용됩니다.

+ {% if user and user.is_super_admin %}

campaign 긴급 공지 만들기·관리 ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)

{% endif %}
diff --git a/app/static/erp-notice-admin.js b/app/static/erp-notice-admin.js new file mode 100644 index 0000000..4de62d3 --- /dev/null +++ b/app/static/erp-notice-admin.js @@ -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 { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[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 = ''; + 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] ? "
  • " + esc(nameOf(e)) + " — " + esc(shortWhen(n.acks[e])) + "
  • " + : '
  • ' + esc(nameOf(e)) + " — 아직 확인 안 함
  • "; + }).join(""); + return '
    ' + + '
    ' + esc(st[1]) + "" + + '' + esc(n.title) + "" + + '' + + '' + + '' + + '" + + "
    " + + '
    띄울 시각 ' + esc(shortWhen(n.show_at)) + " · 받는 사람 " + esc(who) + + " · 만든 사람 " + esc(nameOf(n.created_by)) + "
    " + + '
    ' + esc(ackLine) + "
      " + (rows || "
    • 아직 없습니다
    • ") + "
    " + + "
    "; + }).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(); +})(); diff --git a/app/static/erp-notice.css b/app/static/erp-notice.css new file mode 100644 index 0000000..afba7a0 --- /dev/null +++ b/app/static/erp-notice.css @@ -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; } diff --git a/app/static/erp-notice.js b/app/static/erp-notice.js new file mode 100644 index 0000000..8f0888d --- /dev/null +++ b/app/static/erp-notice.js @@ -0,0 +1,118 @@ +// 긴급 공지 — ERP 모든 화면(erp_base.html) 가운데에 띄운다(2026-10-12). +// · GET /notice/api/pending — 띄울 시각이 지났고 아직 [확인] 안 한 내 공지(오래된 것부터). 30초마다·창을 다시 볼 때. +// · [확인]을 누를 때까지 닫히지 않는다(Esc·바깥 클릭으로 안 닫힘). 여러 건이면 차례대로(1/3). +// · [확인] = POST /notice/api/{id}/ack — 실패하면 창을 그대로 두고 알린다. 다른 탭에서 확인하면 이 탭도 다음 확인 때 닫힌다. +// · 본문 HTML 은 서버가 정리한 것(이미지는 /notice/images/{id} 만). 수신함 오른쪽 작업 창(iframe) 안에서는 돌지 않는다. +// · 024 미적용(503)·로그아웃(401)이면 조용히 멈춘다. +(function () { + "use strict"; + if (window.top !== window) return; // iframe(수신함 작업 창 등) 안에서는 바깥 화면이 띄운다 + const POLL_MS = 30000; + let queue = [], shown = null, box = null, timer = 0, busy = false, stopped = false; + + function esc(s) { + return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { + return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; + }); + } + function when(iso) { + const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || ""); + return m ? m[2] + "/" + m[3] + " " + m[4] + ":" + m[5] : ""; + } + function who(email) { + const id = String(email || "").split("@")[0]; + return id ? id.charAt(0).toUpperCase() + id.slice(1) : ""; + } + function schedule() { clearTimeout(timer); if (!stopped) timer = setTimeout(poll, POLL_MS); } + + async function poll() { + if (busy || stopped) return; + if (document.hidden) { schedule(); return; } + busy = true; + try { + const res = await fetch("/notice/api/pending", { headers: { Accept: "application/json" }, credentials: "same-origin" }); + if (res.status === 401 || res.status === 403 || res.status === 503 || res.status === 404) { stopped = true; return; } + if (!res.ok) return; + const data = await res.json(); + queue = Array.isArray(data.notices) ? data.notices : []; + // 다른 탭·다른 곳에서 확인했거나 취소된 공지는 닫는다 + if (shown && !queue.some(function (n) { return n.id === shown.id; })) close(); + if (!shown && queue.length) open(queue[0]); + else if (shown) paintCount(); + } catch (_) { + // 네트워크 오류는 다음 주기에 다시 + } finally { + busy = false; + schedule(); + } + } + + function paintCount() { + if (!box || !shown) return; + const i = queue.findIndex(function (n) { return n.id === shown.id; }); + const c = box.querySelector(".erp-notice-count"); + c.textContent = queue.length > 1 ? (i + 1) + " / " + queue.length : ""; + c.hidden = queue.length <= 1; + } + function open(n) { + shown = n; + if (!box) { + box = document.createElement("div"); + box.className = "erp-notice-backdrop"; + box.innerHTML = + '
    ' + + '
    긴급 공지
    ' + + '

    ' + + '
    ' + + '' + + '
    ' + + '
    '; + 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(); +})(); diff --git a/app/templates/admin.html b/app/templates/admin.html index c2dd152..e782288 100644 --- a/app/templates/admin.html +++ b/app/templates/admin.html @@ -340,5 +340,8 @@ : `총 ${tbody.querySelectorAll("tr").length}명`; }); - + {# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #} + + + diff --git a/app/templates/erp_base.html b/app/templates/erp_base.html index e657643..9f3ebff 100644 --- a/app/templates/erp_base.html +++ b/app/templates/erp_base.html @@ -8,6 +8,7 @@ + {% block head_extra %}{% endblock %} @@ -95,6 +96,16 @@ 업무 모듈 + {# 긴급 공지 관리 — 수퍼관리자만(app/modules/notice) #} + + + + + + + 긴급 공지 + {% endif %} {% if is_admin %} @@ -179,6 +190,8 @@ 인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #} + {# 긴급 공지 — 로그인한 모든 화면 가운데(받는 사람이 [확인] 전까지). app/modules/notice #} + {% if user %}{% endif %} {% block scripts %}{% endblock %} diff --git a/app/templates/main.html b/app/templates/main.html index 7ab80e8..6d6c43e 100644 --- a/app/templates/main.html +++ b/app/templates/main.html @@ -167,5 +167,8 @@ refreshHealth(); setInterval(refreshHealth, 30000); - + {# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #} + + + diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 141e09b..69fcff6 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -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` 화면은 diff --git a/docs/NOTICE_MODULE.md b/docs/NOTICE_MODULE.md new file mode 100644 index 0000000..f4844f6 --- /dev/null +++ b/docs/NOTICE_MODULE.md @@ -0,0 +1,51 @@ +# 긴급 공지 — `app/modules/notice/` (2026-10-12) + +수퍼관리자가 만든 공지를 **정한 시각**에, **전체 또는 고른 사람**의 ERP 화면 **가로·세로 정가운데**에 띄운다. +받는 사람이 **[확인]을 누를 때까지** 화면을 열 때마다 다시 뜬다(알림 팝업과 달리 닫기·Esc·바깥 클릭으로 안 닫힘). + +## 권한 + +| 할 일 | 누가 | +| --- | --- | +| 공지 만들기·고치기·취소·이미지 올리기·확인 현황(`/notice/`) | 수퍼관리자(`SUPER_ADMIN_EMAIL`)만 — Admin 도 안 됨 | +| 공지 받기·[확인] | 로그인한 등록 사용자(모듈 권한과 무관) — 전체 공지면 모두, 아니면 고른 사람만 | +| 본문 이미지 보기(`/notice/images/{id}`) | 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난, 취소 안 된 공지) | + +들어가는 곳: ERP 왼쪽 아래 **긴급 공지**(수퍼관리자만 보임), Project 화면 오른쪽 위 ⚙(Project 옵션) 안 **긴급 공지 만들기·관리**. + +## 화면 + +- **관리(`/notice/`)** — 제목, 내용(굵게·이미지: 버튼·붙여넣기·끌어 놓기 → 서버에 올리고 주소로 넣음), 띄울 시각(한국시간, + 비우면 바로), 받는 사람(전체 / 고른 사람 — 등록 사용자 목록), [미리 보기](받는 사람 화면과 같은 모양). 목록 = 상태(예약 · 표시 중 · + 취소됨) · 받는 사람 · 확인 현황(확인한 사람·시각, 아직 안 한 사람). [고치기]([이미 확인한 사람에게도 다시 띄우기] 선택 가능) · + [취소](더 띄우지 않음, 기록은 남음) · [취소 되돌리기]. +- **표시(`static/erp-notice.js`)** — `erp_base.html` 을 쓰는 모든 화면 + 업무 모듈 첫 화면(`main.html`)·관리자 페이지(`admin.html`). + `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 멈춤. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index e9c2a73..8234110 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -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`) diff --git a/scripts/sql/project_db_024_urgent_notices.sql b/scripts/sql/project_db_024_urgent_notices.sql new file mode 100644 index 0000000..866c9ae --- /dev/null +++ b/scripts/sql/project_db_024_urgent_notices.sql @@ -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; diff --git a/tests/js/notice_ui.test.js b/tests/js/notice_ui.test.js new file mode 100644 index 0000000..73bf25a --- /dev/null +++ b/tests/js/notice_ui.test.js @@ -0,0 +1,73 @@ +// 긴급 공지 화면(static/erp-notice.js) — jsdom. 가운데 창·차례대로·[확인] 전엔 안 닫힘·확인 실패 유지·다른 곳 확인 반영. +// NODE_PATH= 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("
    화면
    ", { 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, "서버 점검", '

    오늘 18시

    '), 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); }); diff --git a/tests/test_notice.py b/tests/test_notice.py new file mode 100644 index 0000000..51dc38b --- /dev/null +++ b/tests/test_notice.py @@ -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 = ('

    점검 안내

    a' + '
    x') + out = store.sanitize_body(html) + self.assertIn('/notice/images/7', out) + self.assertNotIn("evil.example", out) + self.assertNotIn("data:image", out) + self.assertNotIn("안내", 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"", b"", 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": "

    x

    ", "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"", "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() diff --git a/tests/test_notice_db.py b/tests/test_notice_db.py new file mode 100644 index 0000000..10e5665 --- /dev/null +++ b/tests/test_notice_db.py @@ -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="

    x

    ", 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'

    그림

    ' + 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"", filename="x.svg", by=boss) + + +if __name__ == "__main__": + unittest.main()