"""긴급 공지 저장소 — 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