feat(project): blinking popup for new mentions and task assignments

Project pages poll GET /api/notifications/alerts every 20s (and when the
tab becomes visible). New unread mention/assigned notifications show in a
large blinking popup at the bottom center until closed; closing in one tab
closes it in the others. A new browser starts from the latest id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-07 17:30:15 +09:00
parent 4bdab1de3d
commit 21fc78adb9
5 changed files with 206 additions and 0 deletions
+20
View File
@@ -2292,6 +2292,26 @@ def api_notifications(request: Request) -> JSONResponse:
return JSONResponse({"notifications": items, "unread": _notification_unread(st, user)})
@router.get("/api/notifications/alerts")
def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
"""화면 가운데 아래 큰 팝업용(2026-10-07) — 나를 태그(mention)하거나 작업을 배정(assigned)한, 읽지 않은 알림 중
id 가 after 보다 큰 것(오래된 것부터 최대 10, 지금 볼 수 있는 작업만). after 없이 부르면 기준점(latest_id)만 —
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
user = _require_user(request)
st = _db_or_503(request)
newest = st.list_notifications(recipient_email=user["email"], limit=1)
latest = int(newest[0]["id"]) if newest else 0
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0:
return JSONResponse(out)
rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50)
if n.get("type") in ("mention", "assigned") and int(n["id"]) > after]
rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10]
out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")}
for n in rows]
return JSONResponse(out)
@router.get("/api/notifications/unread-count")
def api_notif_count(request: Request) -> JSONResponse:
user = _require_user(request)
+27
View File
@@ -2847,6 +2847,33 @@ input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
.pj-goal-wkpop-sum b { font-variant-numeric: tabular-nums; }
.pj-goal-wkpop-acts { display: flex; justify-content: flex-end; gap: 6px; margin-top: 10px; }
/* 나를 태그·작업 배정 알림 — 화면 가운데 아래 큰 팝업(body 에 붙음), 닫기 전까지 깜박인다(2026-10-07) */
.pj-alert-pop {
position: fixed; left: 50%; bottom: 28px; z-index: 1100; transform: translateX(-50%); width: min(560px, calc(100vw - 32px));
max-height: 46vh; display: flex; flex-direction: column; background: #fff; border: 2px solid var(--pj-accent);
border-radius: 16px; box-shadow: 0 18px 50px rgba(16, 24, 40, .28); overflow: hidden;
animation: pj-alert-blink 1s ease-in-out infinite;
}
@keyframes pj-alert-blink {
0%, 100% { border-color: var(--pj-accent); box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 0 rgba(124, 92, 255, .55); }
50% { border-color: #ff6b4a; box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 10px rgba(255, 107, 74, .18); }
}
@media (prefers-reduced-motion: reduce) { .pj-alert-pop { animation: none; border-color: #ff6b4a; } }
.pj-alert-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; background: #fff4f0; border-bottom: 1px solid #f6d6cc; }
.pj-alert-head .material-symbols-outlined { color: #e5532f; font-size: 22px; }
.pj-alert-head b { flex: 1 1 auto; font-size: 15px; }
.pj-alert-list { overflow-y: auto; padding: 6px; }
.pj-alert-item { display: flex; align-items: center; gap: 10px; padding: 10px 10px; border-radius: 10px; color: var(--pj-ink); text-decoration: none; }
.pj-alert-item:hover { background: #f5f6f8; }
.pj-alert-kind { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 700; }
.pj-alert-kind.is-mention { background: #eef2ff; color: #4053c8; }
.pj-alert-kind.is-assigned { background: #e7f6ec; color: #1f8a4c; }
.pj-alert-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
.pj-alert-text b { font-size: 14.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-alert-text small { color: var(--pj-ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-alert-go { flex: none; font-size: 12.5px; font-weight: 600; color: var(--pj-accent-dark); }
@media print { .pj-alert-pop { display: none !important; } }
/* 영역 색 고르기 팝업(body 에 붙음) */
.pj-goal-colorpop {
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
+84
View File
@@ -10855,6 +10855,89 @@
if (window.__PJ_TEST__) { // 자동 테스트 전용 — 순수 도우미
window.__pjHelpers = { kstTodayIso: kstTodayIso, dueInfo: dueInfo, isImeEnter: isImeEnter };
}
// ── 나를 태그하거나 새 작업을 배정받으면 화면 가운데 아래 큰 팝업(2026-10-07) — 깜박여서 눈에 띄고, [닫기] 전까지 남는다.
// 프로젝트 화면들이 20초마다(창을 다시 볼 때 바로) GET /project/api/notifications/alerts?after=본 것 을 확인한다.
// 본 것 = localStorage pj_alert_seen:{이메일} — 처음이면 지금 최신 알림을 기준으로 삼아 옛 알림을 한꺼번에 띄우지 않는다.
// 다른 탭에서 닫으면(storage 이벤트) 이 탭 팝업도 닫는다. 수신함 오른쪽 패널(iframe, html.pj-embed) 안에서는 돌지 않는다.
function initTaskAlerts() {
if (document.documentElement.classList.contains("pj-embed")) return;
const POLL_MS = 20000;
let me = "", pop = null, timer = 0, busy = false;
const shown = new Map(); // id → 알림
const seenKey = function () { return "pj_alert_seen:" + me; };
const readSeen = function () { try { const v = localStorage.getItem(seenKey()); return v == null ? null : Number(v); } catch (_) { return null; } };
const writeSeen = function (v) { try { localStorage.setItem(seenKey(), String(v)); } catch (_) {} };
function schedule() { clearTimeout(timer); timer = setTimeout(poll, POLL_MS); }
async function poll() {
if (busy) return;
if (document.hidden) { schedule(); return; }
busy = true;
try {
let after = me ? readSeen() : null;
let res = await api("GET", "/project/api/notifications/alerts" + (after == null ? "" : "?after=" + after));
if (res && res.me && !me) {
me = res.me;
after = readSeen();
if (after == null) writeSeen(res.latest_id || 0); // 처음 — 지금까지 온 알림은 띄우지 않는다
else if (after < (res.latest_id || 0)) res = await api("GET", "/project/api/notifications/alerts?after=" + after);
}
((res && res.alerts) || []).forEach(function (n) { if (!shown.has(n.id)) shown.set(n.id, n); });
if (shown.size) render();
} catch (_) {
// 알림 확인 실패는 조용히 — 다음 주기에 다시
} finally {
busy = false;
schedule();
}
}
function close() {
if (!pop) return;
const maxId = Math.max.apply(null, Array.from(shown.keys()).concat([readSeen() || 0]));
writeSeen(maxId);
shown.clear();
pop.remove();
pop = null;
}
function render() {
if (!pop) {
pop = document.createElement("div");
pop.className = "pj-alert-pop";
pop.setAttribute("role", "alertdialog");
pop.setAttribute("aria-live", "assertive");
document.body.appendChild(pop); // 배율(.pj-ui-scale) 밖 — body 에
pop.addEventListener("click", function (e) {
if (e.target.closest("[data-alert-close]")) close();
const open = e.target.closest("[data-alert-open]");
if (open) {
const id = open.dataset.alertOpen;
fetch("/project/api/notifications/" + id + "/read", { method: "POST" }).catch(function () {});
}
});
}
const items = Array.from(shown.values());
pop.innerHTML = '<div class="pj-alert-head"><span class="material-symbols-outlined">notifications_active</span>' +
"<b>새 알림 " + items.length + "건</b>" +
'<button type="button" class="pj-btn pj-btn-sm" data-alert-close>닫기</button></div>' +
'<div class="pj-alert-list">' + items.map(function (n) {
const isMention = n.type === "mention";
const href = n.project_id ? "/project/p/" + n.project_id + (n.task_id ? "?task=" + n.task_id : "") : "/project/inbox";
return '<a class="pj-alert-item" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' +
'<span class="pj-alert-kind ' + (isMention ? "is-mention" : "is-assigned") + '">' +
(isMention ? "나를 태그" : "작업 배정") + "</span>" +
'<span class="pj-alert-text"><b>' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|작업 배정):\s*/, "")) + "</b>" +
"<small>" + escapeHtml((n.body || "") + (n.actor_email ? " · " + capName(idOf(n.actor_email)) : "")) + "</small></span>" +
'<span class="pj-alert-go">열기 ›</span></a>';
}).join("") + "</div>";
}
window.addEventListener("storage", function (e) {
if (!pop || !me || e.key !== seenKey()) return;
const v = Number(e.newValue || 0);
if (Array.from(shown.keys()).every(function (id) { return id <= v; })) { shown.clear(); pop.remove(); pop = null; }
});
document.addEventListener("visibilitychange", function () { if (!document.hidden) poll(); });
poll();
}
document.addEventListener("DOMContentLoaded", function () {
// 좌측 프로젝트 목록 — 프로젝트 화면은 initProject 가 자기 데이터로 직접 연다.
if (!document.querySelector(".pj-project-view")) initSideTree();
@@ -10867,6 +10950,7 @@
initAllMembers();
initBell();
initMentionBadge();
initTaskAlerts();
initInbox();
initInboxTaskPanel();
initMentionInbox();
+26
View File
@@ -727,6 +727,32 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
check("[대시보드 담당자별] 항목 → 작업 편집 창(하위 작업은 서버에서 받아)", !env.d.getElementById("pj-modal-task").hidden &&
env.d.getElementById("pj-t-title").value === "하위 2", env.d.getElementById("pj-t-title").value);
}
// ── 나를 태그·작업 배정 알림 팝업 — 본 것 이후 새 알림만, 깜박이는 팝업, 닫기 전까지 유지 ──
{
const env = makeEnv(); baseRoutes(env);
const asked = [];
env.route("GET", /\/project\/api\/notifications\/alerts/, function (u) {
asked.push(u);
const after = /after=(\d+)/.exec(u);
if (!after) return { body: { me: "me@test.local", latest_id: 5, alerts: [] } };
return { body: { me: "me@test.local", latest_id: 5, alerts: [
{ id: 4, type: "assigned", title: "작업 배정: 촬영 준비", body: "P1 · 마감 -", task_id: 101, project_id: 1, actor_email: "bob@test.local" },
{ id: 5, type: "mention", title: "나를 태그함: 작업 A", body: "P1 · 댓글", task_id: 101, project_id: 1, actor_email: "bob@test.local" }] } };
});
env.w.localStorage.setItem("pj_alert_seen:me@test.local", "3");
await boot(env); await settle(); await wait(10); await settle();
const pop = env.d.body.querySelector(".pj-alert-pop");
check("[알림 팝업] 본 것(3) 이후 새 알림 2건을 body 에 팝업", !!pop && pop.querySelectorAll(".pj-alert-item").length === 2 &&
/촬영 준비/.test(pop.textContent) && /나를 태그/.test(pop.textContent) && asked.some(function (u) { return /after=3/.test(u); }), asked);
pop.querySelector("[data-alert-close]").click();
check("[알림 팝업] 닫기 → 사라지고 본 것 = 5", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "5");
}
{
const env = makeEnv(); baseRoutes(env);
env.route("GET", /\/project\/api\/notifications\/alerts/, function () { return { body: { me: "me@test.local", latest_id: 9, alerts: [] } }; });
await boot(env); await settle();
check("[알림 팝업] 처음 쓰는 브라우저 — 옛 알림 안 띄우고 기준점만", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "9");
}
// ── 멤버 배정·제외 — 지금 멤버는 체크된 채로, 체크 = 배정 · 해제 = 제외(확인 뒤) ──
{
const env = makeEnv(adminHtml); baseRoutes(env);
+49
View File
@@ -0,0 +1,49 @@
"""알림 팝업 API — 기준점·태그/배정만·읽지 않은 것·after 이후·오래된 것부터. DB 없이 가짜 저장소로."""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
api = importlib.import_module("app.modules.project.router")
ROWS = [ # 최신순(list_notifications 와 같게)
{"id": 9, "type": "completed", "title": "완료", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 7, "type": "assigned", "title": "작업 배정: B", "is_read": True, "task_id": 2, "project_id": 1},
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
{"id": 2, "type": "assigned", "title": "작업 배정: 옛것", "is_read": False, "task_id": 4, "project_id": 1},
]
class FakeStore:
def list_notifications(self, recipient_email, unread_only=False, limit=100):
rows = [r for r in ROWS if not unread_only or not r["is_read"]]
return rows[:limit]
class AlertsApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
def get(self, qs=""):
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
patch.object(api, "_db_or_503", return_value=FakeStore()), \
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
return self.client.get("/project/api/notifications/alerts" + qs).json()
def test_without_after_returns_only_baseline(self):
out = self.get()
self.assertEqual((out["me"], out["latest_id"], out["alerts"]), ("me@test.local", 9, []))
def test_after_returns_unread_mentions_and_assignments_oldest_first(self):
out = self.get("?after=5")
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8]) # 완료 알림(9)·읽은 것(7)·옛것(2) 제외
self.assertEqual(out["alerts"][1]["type"], "mention")
if __name__ == "__main__":
unittest.main()