Files
king c7cc94a09c fix: 2026-10-15 코드 검토 F01~F10 — 수집 실패 전파·트랜잭션 경계·저장 실패·공지 버전/확인 조건·테스트 체계
- F01 쿠팡: HTTP 200 비JSON·data 목록 없음은 수집 실패(기간 교체 안 함), 정상 빈 목록과 구분
- F02 회의록 [적용]: 업무 INSERT 와 줄 연결을 한 연결·한 트랜잭션(_insert_task), 확인은 잠그기 전·알림/메일은 커밋 뒤, 줄 바뀜 409
- F03 업무 등록 표: persist 실패 전파, 미저장이면 [적용] 중단, 초안 유지·다시 저장·이탈 경고
- F04 인증정보 변경 시 내부 토큰 삭제 + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음, GS샵 방식 캐시도 키 지문 기준
- F05 쪽 수 상한·커서 반복 = 실패(쿠팡은 구간을 하루까지 나눠 재시도), 네이버·카카오·토스·GS샵 동일 기준
- F06 [중지] 확인과 저장 시작을 같은 잠금(begin_saving), 저장 시작 뒤 중지 불가
- F07/F08 긴급 공지: 내용 version·고친 공지 다시 그리기·확인에 version(409), 확인은 행 잠금 트랜잭션에서 수신자·표시 시각·취소 검증
- F09 쇼핑몰 연결 테스트도 clear 처리·저장 안 한 시험은 상태 유지(광고 테스트와 같은 계약)
- F10 DB 테스트 skip·가짜 app.main/time.sleep 파일 범위 fixture, 오래된 기대값 갱신, pytest.ini·requirements-dev·tests/js/package.json·docs/TESTING.md
- 결과·후속 과제: docs/CODE_REVIEW_2026-10-15_RESULT.md (마이그레이션·환경변수 변경 없음)

Python 440 passed/63 skipped(DB 없음), 503 passed(로컬 PostgreSQL), jsdom 7종·Edge 6종 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:41:42 +09:00

239 lines
13 KiB
Python

"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
from __future__ import annotations
from datetime import datetime, timezone
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 ""
def _version(v: Any) -> str:
"""공지 내용 버전 = updated_at(마이크로초까지, UTC) — 고치기·취소 때마다 바뀐다. 받는 사람 화면이 바뀐 내용을 다시 그리고,
[확인]이 어느 내용을 읽고 누른 것인지 서버가 가린다(2026-10-15 검토 F07)."""
return v.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S%f") 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")),
"version": _version(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, version: str | None = None, now: datetime | None = None) -> str:
"""[확인] — 결과: "acked"(처음) · "already"(이미 확인 — 여러 번 눌러도 한 번) · "stale"(그 사이 내용이 바뀜 — 읽은
version 이 지금과 다름) · "denied"(받는 사람이 아님·띄울 시각 전·취소·없음).
받는 사람·표시 시각·취소 확인과 기록이 **한 트랜잭션**(2026-10-15 검토 F08): 공지 행을 FOR SHARE 로 잠그고 조건을 본 뒤
기록한다 — 동시에 취소·고치기가 들어오면 그 쪽이 먼저 끝나거나(그러면 바뀐 행으로 다시 판정) 이 기록 뒤로 기다린다.
version 이 없으면(예전 화면) 내용 확인은 건너뛴다."""
em = pj_store.norm_str(email, lower=True)
def run() -> str:
with self._conn() as conn:
with conn.transaction():
n = conn.execute(
"SELECT n.id, n.updated_at FROM urgent_notices n "
"WHERE n.id = %s AND 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)) "
"FOR SHARE OF n",
(notice_id, now or datetime.now(KST), em),
).fetchone()
if n is None:
return "denied"
done = conn.execute("SELECT 1 FROM urgent_notice_acks WHERE notice_id = %s AND user_email = %s",
(notice_id, em)).fetchone()
if done is not None:
return "already"
if version and version != _version(n["updated_at"]):
return "stale"
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
"ON CONFLICT DO NOTHING RETURNING notice_id", (notice_id, em)).fetchone()
return "acked" if r is not None else "already"
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