2aa6b6efae
- 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>
184 lines
8.2 KiB
Python
184 lines
8.2 KiB
Python
"""긴급 공지 라우터(/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)
|