diff --git a/client/src/api/notifications.ts b/client/src/api/notifications.ts index 3461b47a..e2f74e99 100644 --- a/client/src/api/notifications.ts +++ b/client/src/api/notifications.ts @@ -24,6 +24,7 @@ export type NotificationListQuery = { page?: number; pageSize?: number; unreadOnly?: boolean; + type?: string; }; function toQueryString(query: NotificationListQuery) { @@ -31,6 +32,7 @@ function toQueryString(query: NotificationListQuery) { if (query.page != null) params.set("page", String(query.page)); if (query.pageSize != null) params.set("pageSize", String(query.pageSize)); if (query.unreadOnly != null) params.set("unreadOnly", query.unreadOnly ? "1" : "0"); + if (query.type) params.set("type", query.type); const qs = params.toString(); return qs ? `?${qs}` : ""; } @@ -49,3 +51,9 @@ export async function markNotificationRead(notificationId: string) { ); } +export async function markAllNotificationsRead() { + return apiRequestData<{ updatedCount: number }>("/api/notifications/mark-all-read", { + method: "POST", + body: JSON.stringify({}), + }); +} diff --git a/client/src/components/navigation/Topbar.tsx b/client/src/components/navigation/Topbar.tsx index 2e7152d4..fd1e8eb1 100644 --- a/client/src/components/navigation/Topbar.tsx +++ b/client/src/components/navigation/Topbar.tsx @@ -1,9 +1,12 @@ import { useEffect, useState } from "react"; -import { Link, useLocation } from "react-router-dom"; -import { useQuery } from "@tanstack/react-query"; -import { fetchNotifications } from "../../api/notifications"; +import { Link, useLocation, useNavigate } from "react-router-dom"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import type { NotificationItem } from "../../api/notifications"; +import { fetchNotifications, markAllNotificationsRead, markNotificationRead } from "../../api/notifications"; import { useAuth } from "../../auth/AuthContext"; import { resolvePageMeta } from "../../features/navigation/schema"; +import { resolveNotificationTargetLink, formatNotificationRelativeTime } from "../../lib/notificationLinks"; +import { resolveErrorMessage } from "../../lib/resolveErrorMessage"; import { isWecomWebView } from "../../lib/runtimeContext"; import { GlobalSearchDialog } from "../GlobalSearchDialog"; import { AppBrand } from "../shell/AppBrand"; @@ -17,6 +20,7 @@ import { DropdownMenuTrigger, } from "../ui/dropdown-menu"; import { NavLinks } from "./NavLinks"; +import { toast } from "sonner"; function MenuIcon() { return ( @@ -43,8 +47,11 @@ function BellIcon() { export function Topbar() { const { me, logout } = useAuth(); const location = useLocation(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); const [mobileNavOpen, setMobileNavOpen] = useState(false); const [searchOpen, setSearchOpen] = useState(false); + const [notificationsOpen, setNotificationsOpen] = useState(false); const wecomEntry = isWecomWebView(); const pageMeta = resolvePageMeta(location.pathname); @@ -55,9 +62,47 @@ export function Topbar() { refetchInterval: 30_000, }); + const dropdownQuery = useQuery({ + enabled: Boolean(me) && notificationsOpen, + queryKey: ["notifications", "dropdown"], + queryFn: () => fetchNotifications({ page: 1, pageSize: 5 }), + }); + + const markReadMutation = useMutation({ + mutationFn: (notificationId: string) => markNotificationRead(notificationId), + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: ["notifications"] }); + }, + }); + + const markAllReadMutation = useMutation({ + mutationFn: () => markAllNotificationsRead(), + onSuccess: async () => { + toast.success("已全部标为已读"); + await queryClient.invalidateQueries({ queryKey: ["notifications"] }); + }, + onError: (error) => { + toast.error(resolveErrorMessage(error)); + }, + }); + const unreadCount = unreadQuery.data?.unreadCount ?? 0; const unreadBadge = unreadCount > 99 ? "99+" : String(unreadCount); + const handleNotificationClick = async (item: NotificationItem) => { + const targetLink = resolveNotificationTargetLink(item) ?? "/notifications"; + + try { + if (!item.readAt) { + await markReadMutation.mutateAsync(item.id); + } + setNotificationsOpen(false); + navigate(targetLink); + } catch (error) { + toast.error(resolveErrorMessage(error)); + } + }; + useEffect(() => { const handleKeydown = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) { @@ -160,16 +205,88 @@ export function Topbar() { search - + + + + + + +
+
+ 通知 + + {unreadCount} + +
+ +
+ +
+ {dropdownQuery.isLoading ? ( +
通知加载中...
+ ) : null} + + {dropdownQuery.isError ? ( +
{resolveErrorMessage(dropdownQuery.error)}
+ ) : null} + + {!dropdownQuery.isLoading && !dropdownQuery.isError ? ( + dropdownQuery.data?.items?.length ? ( + dropdownQuery.data.items.map((item) => ( + + )) + ) : ( +
暂无通知
+ ) + ) : null} +
+ +
+ +
+
+
diff --git a/client/src/lib/notificationLinks.ts b/client/src/lib/notificationLinks.ts new file mode 100644 index 00000000..1342e0c5 --- /dev/null +++ b/client/src/lib/notificationLinks.ts @@ -0,0 +1,75 @@ +type NotificationTarget = { + targetType: string | null; + targetId: string | null; +}; + +export function resolveNotificationTargetLink(item: NotificationTarget) { + if (!item.targetType || !item.targetId) return null; + + if (item.targetType === "workflow_task") { + return `/workflow/tasks/${item.targetId}`; + } + + if (item.targetType === "reimbursement_form") { + return `/reimbursements/${item.targetId}`; + } + + if (item.targetType === "leave_request") { + return `/leave-requests?highlight=${item.targetId}`; + } + + if (item.targetType === "purchase_request") { + return `/purchase-requests?highlight=${item.targetId}`; + } + + if (item.targetType === "travel_request") { + return `/travel-requests?highlight=${item.targetId}`; + } + + if (item.targetType === "asset" || item.targetType === "asset_card") { + return `/assets?highlight=${item.targetId}`; + } + + if (item.targetType === "inventory_check") { + return `/inventory-checks?highlight=${item.targetId}`; + } + + if (item.targetType === "employee") { + return "/settings/profile"; + } + + return null; +} + +export function formatNotificationRelativeTime(value: string | null) { + if (!value) { + return "-"; + } + + const timestamp = new Date(value).getTime(); + if (Number.isNaN(timestamp)) { + return "-"; + } + + const diffMs = Date.now() - timestamp; + if (diffMs < 60 * 1000) { + return "刚刚"; + } + + const diffMinutes = Math.floor(diffMs / (60 * 1000)); + if (diffMinutes < 60) { + return `${diffMinutes} 分钟前`; + } + + const diffHours = Math.floor(diffMinutes / 60); + if (diffHours < 24) { + return `${diffHours} 小时前`; + } + + const diffDays = Math.floor(diffHours / 24); + if (diffDays < 7) { + return `${diffDays} 天前`; + } + + return new Date(value).toLocaleDateString("zh-CN"); +} diff --git a/client/src/pages/NotificationsPage.tsx b/client/src/pages/NotificationsPage.tsx index 54276811..56f53e0a 100644 --- a/client/src/pages/NotificationsPage.tsx +++ b/client/src/pages/NotificationsPage.tsx @@ -1,12 +1,15 @@ import { Link, useSearchParams } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { fetchNotifications, markNotificationRead } from "../api/notifications"; +import { toast } from "sonner"; +import { fetchNotifications, markAllNotificationsRead, markNotificationRead } from "../api/notifications"; import { isApiError } from "../api/types"; import { mapApiErrorMessage } from "../api/errorMessages"; import { PageHeader } from "../components/common/PageHeader"; import { TableSkeleton } from "../components/common/TableSkeleton"; import { Pagination } from "../components/common/Pagination"; import { Button } from "../components/ui/button"; +import { resolveNotificationTargetLink } from "../lib/notificationLinks"; +import { resolveErrorMessage } from "../lib/resolveErrorMessage"; import { Table, TableBody, @@ -19,23 +22,16 @@ import { Tabs, TabsList, TabsTrigger } from "../components/ui/tabs"; const PAGE_SIZE = 20; -function resolveTargetLink(item: { targetType: string | null; targetId: string | null }) { - if (!item.targetType || !item.targetId) return null; - - if (item.targetType === "workflow_task") { - return `/workflow/tasks/${item.targetId}`; - } - - if (item.targetType === "reimbursement_form") { - return `/reimbursements/${item.targetId}`; - } - - if (item.targetType === "employee") { - return "/settings/profile"; - } - - return null; -} +const NOTIFICATION_TYPE_OPTIONS = [ + { label: "全部", value: "" }, + { label: "审批待办", value: "workflow.task_assigned" }, + { label: "报销", value: "reimbursement.approved,reimbursement.rejected,reimbursement.returned,reimbursement.paid" }, + { label: "请假", value: "leave.approved,leave.rejected" }, + { label: "采购", value: "purchase_request.approved,purchase_request.rejected" }, + { label: "差旅", value: "travel_request.approved,travel_request.rejected" }, + { label: "资产", value: "asset.assigned,asset.returned,asset.transferred" }, + { label: "盘点", value: "inventory_check.completed" }, +]; export function NotificationsPage() { const queryClient = useQueryClient(); @@ -44,24 +40,45 @@ export function NotificationsPage() { const unreadOnlyRaw = searchParams.get("unreadOnly") ?? "0"; const unreadOnly = unreadOnlyRaw === "1" || unreadOnlyRaw === "true"; const page = Number(searchParams.get("page") ?? "1") || 1; + const selectedType = searchParams.get("type") ?? ""; + + const updateFilters = (next: { unreadOnly?: boolean; page?: number; type?: string }) => { + const params = new URLSearchParams(); + params.set("unreadOnly", (next.unreadOnly ?? unreadOnly) ? "1" : "0"); + params.set("page", String(next.page ?? page)); + const nextType = next.type ?? selectedType; + if (nextType) { + params.set("type", nextType); + } + setSearchParams(params); + }; const listQuery = useQuery({ - queryKey: ["notifications", "list", unreadOnly, page], + queryKey: ["notifications", "list", unreadOnly, selectedType, page], queryFn: () => fetchNotifications({ unreadOnly, page, pageSize: PAGE_SIZE, + ...(selectedType ? { type: selectedType } : {}), }), }); const markReadMutation = useMutation({ mutationFn: async (notificationId: string) => markNotificationRead(notificationId), onSuccess: async () => { - await Promise.all([ - queryClient.invalidateQueries({ queryKey: ["notifications"] }), - queryClient.invalidateQueries({ queryKey: ["notifications", "unread-count"] }), - ]); + await queryClient.invalidateQueries({ queryKey: ["notifications"] }); + }, + }); + + const markAllReadMutation = useMutation({ + mutationFn: () => markAllNotificationsRead(), + onSuccess: async () => { + toast.success("已全部标为已读"); + await queryClient.invalidateQueries({ queryKey: ["notifications"] }); + }, + onError: (error) => { + toast.error(resolveErrorMessage(error)); }, }); @@ -73,33 +90,67 @@ export function NotificationsPage() { title="通知" subtitle="站内通知与待办提醒。" actions={ - + <> + + + } />
- - setSearchParams({ - unreadOnly: value === "unread" ? "1" : "0", - page: "1", - }) - } - > - - - 全部 - - - 未读 - - - +
+ + updateFilters({ + unreadOnly: value === "unread", + page: 1, + }) + } + > + + + 全部 + + + 未读 + + + + + +
未读 {listQuery.data?.unreadCount ?? 0} 条 @@ -134,7 +185,7 @@ export function NotificationsPage() { {(listQuery.data?.items ?? []).length ? ( listQuery.data?.items.map((item) => { - const targetLink = resolveTargetLink(item); + const targetLink = resolveNotificationTargetLink(item); return ( @@ -189,11 +240,14 @@ export function NotificationsPage() { setSearchParams({ unreadOnly: unreadOnly ? "1" : "0", page: String(p) })} + onPageChange={(p) => + updateFilters({ + page: p, + }) + } testIdPrefix="notifications" />
); } - diff --git a/issues/2026-04-14_r63-notification-ux.csv b/issues/2026-04-14_r63-notification-ux.csv new file mode 100644 index 00000000..e57b567b --- /dev/null +++ b/issues/2026-04-14_r63-notification-ux.csv @@ -0,0 +1,7 @@ +ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes +"A1","R63 执行合同建档与范围冻结","创建并校验 R63 通知中心体验增强执行合同 CSV,冻结范围:1) 后端新增 POST /api/notifications/mark-all-read;2) GET /api/notifications 增加 type 过滤;3) 前端通知页增加批量已读、类型筛选、深链补全;4) Topbar 铃铛增加最近 5 条通知下拉。不新增 Prisma 迁移,不新增 npm 依赖。","issues/2026-04-14_r63-notification-ux.csv 列完整、Dependencies 为 JSON 数组字符串、A2-A6 范围与方案一致,且 Notes 明确唯一新增后端路由、无迁移、无新依赖与回滚路径。","命令:python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-04-14_r63-notification-ux.csv。检查:1) 12 列完整;2) A2-A6 依赖链合理;3) Notes 明确无迁移、无新依赖、唯一新增后端路由与回滚路径。","manual","DONE","DONE","DONE","issues/2026-04-14_r63-notification-ux.csv","[]","回滚路径:删除本次 CSV 不影响业务。" +"A2","后端通知列表类型过滤与批量已读","在 server/src/routes/notifications.js 为 GET /api/notifications 增加逗号分隔的 type 查询参数,并新增 POST /api/notifications/mark-all-read;保持 unreadCount 为全部未读总数,不受 type 过滤影响。扩展现有 notifications 单测覆盖类型过滤与批量已读幂等。","1) GET /api/notifications 支持 type=leave.approved,leave.rejected 过滤;2) total 跟随过滤结果;3) unreadCount 仍返回全部未读总数;4) POST /api/notifications/mark-all-read 返回 updatedCount:number 且重复调用幂等;5) node --check 与 notifications.test.js 通过。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && node --check src/routes/notifications.js && npm test -- tests/unit/routes/notifications.test.js。业务:1) type=leave.approved 时仅返回对应类型;2) 调用 mark-all-read 后当前用户未读全部变为已读;3) 再次调用 updatedCount=0;4) unreadCount 不受 type 过滤影响。","manual","DONE","DONE","DONE","server/src/routes/notifications.js|server/tests/unit/routes/notifications.test.js","[""A1""]","回滚路径:移除 type 过滤与 mark-all-read 端点代码及相关测试。无 Prisma 迁移,无新依赖。唯一新增后端路由:POST /api/notifications/mark-all-read。" +"A3","前端通知页批量已读、类型筛选与深链补全","在 client/src/pages/NotificationsPage.tsx 增加“全部标为已读”按钮、类型筛选下拉与完整深链映射;在 client/src/api/notifications.ts 增加 type 查询参数与 markAllNotificationsRead API。","1) 通知页可按审批待办/报销/请假/采购/差旅/资产/盘点过滤;2) 点击全部标为已读后出现成功 toast 并刷新列表与未读数;3) unreadCount=0 或请求中时按钮禁用;4) leave_request、purchase_request、travel_request、asset/asset_card、inventory_check 深链正确跳转;5) typecheck 与 build 通过。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) /notifications 可见类型筛选与全部标为已读按钮;2) 切换类型后列表变化且分页回到第 1 页;3) 点击通知查看能跳到对应业务页面。","manual","DONE","DONE","DONE","client/src/api/notifications.ts|client/src/pages/NotificationsPage.tsx|client/src/lib/notificationLinks.ts","[""A1"",""A2""]","回滚路径:移除批量已读按钮、类型筛选、通知深链补全及对应 API 接口封装。无 Prisma 迁移,无新依赖。唯一新增后端路由:POST /api/notifications/mark-all-read。" +"A4","Topbar 铃铛通知下拉面板","在 client/src/components/navigation/Topbar.tsx 将铃铛改为下拉面板,展示最近 5 条通知、未读数、全部标为已读入口与查看全部链接;点击通知可标记已读后跳转目标页面。","1) 铃铛点击展开面板,外部点击或 ESC 可关闭;2) 面板展示最近 5 条通知、相对时间、未读蓝点与查看全部链接;3) 全部标为已读入口可刷新未读数与列表;4) 点击未读通知会先标已读再跳转目标页面;5) typecheck 与 build 通过。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 顶栏铃铛可展开最近 5 条通知下拉;2) 点击通知可跳转且面板关闭;3) 底部查看全部链接到 /notifications;4) 相对时间展示为刚刚/X 分钟前/X 小时前/X 天前/日期。","manual","DONE","DONE","DONE","client/src/components/navigation/Topbar.tsx|client/src/api/notifications.ts|client/src/lib/notificationLinks.ts","[""A1"",""A2""]","回滚路径:恢复铃铛为直接跳转 /notifications 的 Link,移除下拉面板与最近 5 条通知查询。无 Prisma 迁移,无新依赖。唯一新增后端路由:POST /api/notifications/mark-all-read。" +"A5","测试与回归验证","执行 R63 后端 notifications 测试与前端 typecheck/build,确认批量已读、类型筛选与铃铛面板未引入回归。","1) server/src/routes/notifications.js 语法检查通过;2) notifications 路由单测通过;3) client typecheck/build 通过;4) 手工预期与 OpenClaw 场景一致:通知页可批量已读、类型筛选有效、铃铛面板可展开并跳转。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && node --check src/routes/notifications.js && npm test -- tests/unit/routes/notifications.test.js && cd ../client && npm run typecheck && npm run build。业务:检查通知页与 Topbar 铃铛的核心路径均按预期工作。","manual","DONE","DONE","DONE","server/src/routes/notifications.js|server/tests/unit/routes/notifications.test.js|client/src/api/notifications.ts|client/src/pages/NotificationsPage.tsx|client/src/components/navigation/Topbar.tsx|client/src/lib/notificationLinks.ts","[""A2"",""A3"",""A4""]","回滚路径:若 post-check 失败,暂停提交并回退对应 R63 代码。无 Prisma 迁移,无新依赖。" +"A6","QA、状态回填与提交收口","在验证通过后回填 R63 CSV 状态,确认后端测试与前端构建全部通过,并完成 git commit 收口。","1) issues/2026-04-14_r63-notification-ux.csv 的 Dev_Status、Review1_Status、Regression_Status 均按实测结果回填;2) 所有验证命令通过;3) git commit 成功,提交信息为 R63 A1-A6:通知中心体验增强。","命令:1) python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-04-14_r63-notification-ux.csv;2) export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && node --check src/routes/notifications.js && npm test -- tests/unit/routes/notifications.test.js && cd ../client && npm run typecheck && npm run build;3) git status 确认变更范围。业务:核对通知页与铃铛面板的最终行为与方案一致。","manual","DONE","DONE","DONE","issues/2026-04-14_r63-notification-ux.csv|server/src/routes/notifications.js|server/tests/unit/routes/notifications.test.js|client/src/api/notifications.ts|client/src/pages/NotificationsPage.tsx|client/src/components/navigation/Topbar.tsx|client/src/lib/notificationLinks.ts","[""A5""]","回滚路径:若验证失败则不提交,先修复后再回填状态。commit message:R63 A1-A6:通知中心体验增强。无 Prisma 迁移,无新依赖。" diff --git a/server/src/routes/notifications.js b/server/src/routes/notifications.js index b47cdbd3..51503aae 100644 --- a/server/src/routes/notifications.js +++ b/server/src/routes/notifications.js @@ -18,6 +18,7 @@ const LIST_QUERY_SCHEMA = z.object({ page: z.coerce.number().int().min(1).optional(), pageSize: z.coerce.number().int().min(1).max(100).optional(), unreadOnly: z.enum(['0', '1', 'true', 'false']).optional(), + type: z.string().optional(), }); const DELIVERY_STATUS_VALUES = Object.freeze(['pending', 'success', 'failed']); const DELIVERY_QUERY_SCHEMA = z.object({ @@ -140,11 +141,18 @@ function parseListQuery(query) { const pageSize = parsed.data.pageSize ?? 20; const unreadOnlyRaw = parsed.data.unreadOnly ?? '0'; const unreadOnly = unreadOnlyRaw === '1' || unreadOnlyRaw === 'true'; + const types = uniqStrings( + String(parsed.data.type ?? '') + .split(',') + .map((item) => item.trim()) + .filter(Boolean), + ); return { page, pageSize, unreadOnly, + types, }; } @@ -362,6 +370,7 @@ async function notificationsRoutes(fastify) { const where = { recipient_employee_id: request.employee.id, ...(query.unreadOnly ? { read_at: null } : {}), + ...(query.types.length ? { type: { in: query.types } } : {}), }; const [items, total, unreadCount] = await Promise.all([ @@ -401,6 +410,28 @@ async function notificationsRoutes(fastify) { }, ); + fastify.post( + '/notifications/mark-all-read', + { + preHandler: fastify.authenticate, + }, + async (request, reply) => { + const result = await fastify.prisma.notification.updateMany({ + where: { + recipient_employee_id: request.employee.id, + read_at: null, + }, + data: { + read_at: new Date(), + }, + }); + + return sendData(reply, request, { + updatedCount: Number(result?.count ?? 0), + }); + }, + ); + fastify.post( '/notifications/:id/mark-read', { diff --git a/server/tests/unit/routes/notifications.test.js b/server/tests/unit/routes/notifications.test.js index d9bd5821..a531bcd2 100644 --- a/server/tests/unit/routes/notifications.test.js +++ b/server/tests/unit/routes/notifications.test.js @@ -68,9 +68,39 @@ function buildDeliveryRecord(overrides = {}) { }; } -function createPrismaState({ channels = [], deliveries = [] } = {}) { +function applySelect(record, select) { + if (!select) { + return { ...record }; + } + + return Object.fromEntries( + Object.entries(select) + .filter(([, enabled]) => Boolean(enabled)) + .map(([key]) => [key, record[key]]), + ); +} + +function matchNotificationWhere(item, where = {}) { + if (where.recipient_employee_id && item.recipient_employee_id !== where.recipient_employee_id) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(where, 'read_at') && where.read_at === null && item.read_at !== null) { + return false; + } + + const typeFilter = where.type?.in ?? null; + if (Array.isArray(typeFilter) && typeFilter.length > 0 && !typeFilter.includes(item.type)) { + return false; + } + + return true; +} + +function createPrismaState({ channels = [], deliveries = [], notifications = [] } = {}) { const stateChannels = channels.map((channel) => ({ ...channel })); const stateDeliveries = deliveries.map((delivery) => ({ ...delivery })); + const stateNotifications = notifications.map((notification) => ({ ...notification })); const auditEntries = []; const notificationChannel = { @@ -151,8 +181,60 @@ function createPrismaState({ channels = [], deliveries = [] } = {}) { }), }; + const notification = { + findMany: vi.fn().mockImplementation(async ({ where, skip, take, select }) => { + const items = stateNotifications + .filter((item) => matchNotificationWhere(item, where)) + .sort((left, right) => right.created_at.getTime() - left.created_at.getTime()) + .slice(skip ?? 0, (skip ?? 0) + (take ?? stateNotifications.length)) + .map((item) => applySelect(item, select)); + return items; + }), + count: vi.fn().mockImplementation(async ({ where }) => stateNotifications.filter((item) => matchNotificationWhere(item, where)).length), + updateMany: vi.fn().mockImplementation(async ({ where, data }) => { + let count = 0; + stateNotifications.forEach((item, index) => { + if (!matchNotificationWhere(item, where)) { + return; + } + + stateNotifications[index] = { + ...item, + ...data, + }; + count += 1; + }); + return { count }; + }), + findUnique: vi.fn().mockImplementation(async ({ where, select }) => { + const item = stateNotifications.find((notificationItem) => notificationItem.id === where.id); + return item ? applySelect(item, select) : null; + }), + update: vi.fn().mockImplementation(async ({ where, data, select }) => { + const index = stateNotifications.findIndex((item) => item.id === where.id); + if (index < 0) { + return null; + } + + stateNotifications[index] = { + ...stateNotifications[index], + ...data, + }; + + return applySelect(stateNotifications[index], select); + }), + }; + + const transactionClient = { + notification, + $queryRaw: vi.fn().mockImplementation(async (_strings, notificationId) => { + return stateNotifications.some((item) => item.id === notificationId) ? [{ id: notificationId }] : []; + }), + }; + return { prisma: { + notification, notificationChannel, notificationDelivery: { findMany: vi.fn().mockImplementation(async ({ where, take }) => { @@ -180,8 +262,10 @@ function createPrismaState({ channels = [], deliveries = [] } = {}) { return { id: `audit-${auditEntries.length}` }; }), }, + $transaction: vi.fn().mockImplementation(async (callback) => callback(transactionClient)), }, stateChannels, + stateNotifications, auditEntries, }; } @@ -576,3 +660,135 @@ describe('notifications channel routes', () => { await app.close(); }); }); + +describe('notification inbox routes', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('filters notifications by type while keeping unreadCount global', async () => { + const { prisma } = createPrismaState({ + notifications: [ + buildNotificationRecord({ + id: '10000000-0000-4000-8000-000000000001', + recipient_employee_id: 'employee-1', + type: 'leave.approved', + created_at: new Date('2026-03-13T11:00:00.000Z'), + }), + buildNotificationRecord({ + id: '10000000-0000-4000-8000-000000000002', + recipient_employee_id: 'employee-1', + type: 'reimbursement.approved', + created_at: new Date('2026-03-13T10:00:00.000Z'), + }), + buildNotificationRecord({ + id: '10000000-0000-4000-8000-000000000003', + recipient_employee_id: 'employee-1', + type: 'leave.approved', + read_at: new Date('2026-03-13T09:30:00.000Z'), + created_at: new Date('2026-03-13T09:00:00.000Z'), + }), + buildNotificationRecord({ + id: '10000000-0000-4000-8000-000000000004', + recipient_employee_id: 'employee-9', + type: 'leave.approved', + created_at: new Date('2026-03-13T08:00:00.000Z'), + }), + ], + }); + const app = await buildApp({ prisma }); + + const response = await app.inject({ + method: 'GET', + url: '/api/notifications?type=leave.approved', + headers: { authorization: 'Bearer test-token' }, + }); + + expect(response.statusCode).toBe(200); + expect(response.json().data.total).toBe(2); + expect(response.json().data.unreadCount).toBe(2); + expect(response.json().data.items).toEqual([ + expect.objectContaining({ + id: '10000000-0000-4000-8000-000000000001', + type: 'leave.approved', + }), + expect.objectContaining({ + id: '10000000-0000-4000-8000-000000000003', + type: 'leave.approved', + }), + ]); + + await app.close(); + }); + + it('marks all unread notifications as read for current employee', async () => { + const { prisma, stateNotifications } = createPrismaState({ + notifications: [ + buildNotificationRecord({ + id: '20000000-0000-4000-8000-000000000001', + recipient_employee_id: 'employee-1', + read_at: null, + }), + buildNotificationRecord({ + id: '20000000-0000-4000-8000-000000000002', + recipient_employee_id: 'employee-1', + type: 'leave.approved', + read_at: null, + created_at: new Date('2026-03-13T08:00:00.000Z'), + }), + buildNotificationRecord({ + id: '20000000-0000-4000-8000-000000000003', + recipient_employee_id: 'employee-1', + read_at: new Date('2026-03-13T07:00:00.000Z'), + }), + buildNotificationRecord({ + id: '20000000-0000-4000-8000-000000000004', + recipient_employee_id: 'employee-2', + read_at: null, + }), + ], + }); + const app = await buildApp({ prisma }); + + const response = await app.inject({ + method: 'POST', + url: '/api/notifications/mark-all-read', + headers: { authorization: 'Bearer test-token' }, + payload: {}, + }); + + expect(response.statusCode).toBe(200); + expect(response.json().data).toEqual({ updatedCount: 2 }); + expect(stateNotifications.filter((item) => item.recipient_employee_id === 'employee-1' && item.read_at === null)).toHaveLength(0); + expect( + stateNotifications.find((item) => item.id === '20000000-0000-4000-8000-000000000004')?.read_at, + ).toBeNull(); + + await app.close(); + }); + + it('keeps mark-all-read idempotent when there are no unread notifications', async () => { + const { prisma } = createPrismaState({ + notifications: [ + buildNotificationRecord({ + id: '30000000-0000-4000-8000-000000000001', + recipient_employee_id: 'employee-1', + read_at: new Date('2026-03-13T07:00:00.000Z'), + }), + ], + }); + const app = await buildApp({ prisma }); + + const response = await app.inject({ + method: 'POST', + url: '/api/notifications/mark-all-read', + headers: { authorization: 'Bearer test-token' }, + payload: {}, + }); + + expect(response.statusCode).toBe(200); + expect(response.json().data).toEqual({ updatedCount: 0 }); + + await app.close(); + }); +});