Files
dbx-main/app/modules/notice/store.py
T
king 2aa6b6efae feat(notice): urgent notices centered on every ERP screen until acknowledged
- Super admin only: /notice/ page (title, body with images, show time KST, all or picked people,
  preview, edit with optional re-show, cancel/undo, per-person acknowledgement status)
- Shown on every ERP page (erp_base, main, admin) dead center; [확인] only (no Esc/backdrop close),
  queue in order, ack failure keeps the dialog, closes when acked/cancelled elsewhere
- project_db migration 024 (urgent_notices, targets, acks, images as bytea); shares ProjectStore.pool
- Body sanitized like task descriptions, images restricted to /notice/images/{id}, type sniffed
- Entry points: ERP sidebar foot and Project options dialog (super admin)
- Docs (NOTICE_MODULE, DEPLOYMENT 024, overview, CLAUDE.md); tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:07:10 +09:00

107 lines
4.1 KiB
Python

"""긴급 공지 — 순수 검증(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)만 올릴 수 있습니다.")