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>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
// 긴급 공지 화면(static/erp-notice.js) — jsdom. 가운데 창·차례대로·[확인] 전엔 안 닫힘·확인 실패 유지·다른 곳 확인 반영.
|
||||
// NODE_PATH=<jsdom 경로> 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("<!doctype html><body><main>화면</main></body>", { 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, "서버 점검", '<p>오늘 <b>18시</b></p><img src="/notice/images/3">'), 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); });
|
||||
@@ -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 = ('<p>점검 <b>안내</b></p><img src="/notice/images/7" alt="a"><img src="https://evil.example/x.png">'
|
||||
'<img src="data:image/png;base64,AAAA"><script>alert(1)</script><a href="javascript:alert(1)">x</a>')
|
||||
out = store.sanitize_body(html)
|
||||
self.assertIn('/notice/images/7', out)
|
||||
self.assertNotIn("evil.example", out)
|
||||
self.assertNotIn("data:image", out)
|
||||
self.assertNotIn("<script", out)
|
||||
self.assertNotIn("javascript:", out)
|
||||
self.assertIn("<b>안내</b>", 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"<svg onload=alert(1)>", b"<html>", 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": "<p>x</p>", "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"<svg/>", "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()
|
||||
@@ -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="<p>x</p>", 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'<p>그림</p><img src="{mine["url"]}"><img src="{theirs["url"]}">'
|
||||
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"<svg/>", filename="x.svg", by=boss)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user