R63 A1-A6:通知中心体验增强

这个提交包含在:
2026-04-14 14:14:10 +08:00
父节点 c90cb165be
当前提交 86644a6766
共修改 7 个文件,包含 570 行新增和 62 行删除
+8
查看文件
@@ -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({}),
});
}
+122 -5
查看文件
@@ -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() {
<span className="material-symbols-outlined text-[18px]">search</span>
</Button>
<Button asChild size="icon" variant="secondary" aria-label="通知" type="button" data-testid="notifications-bell">
<Link className="relative" to="/notifications">
<DropdownMenu open={notificationsOpen} onOpenChange={setNotificationsOpen}>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="secondary"
aria-label="通知"
type="button"
data-testid="notifications-bell"
className="relative"
>
<BellIcon />
{unreadCount > 0 ? (
<span className="absolute -right-2 -top-2 min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-white">
{unreadBadge}
</span>
) : null}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 max-w-[calc(100vw-2rem)] p-0">
<div className="flex items-center justify-between border-b border-zinc-200 px-4 py-3">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-zinc-900">通知</span>
<span className="rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600">
{unreadCount}
</span>
</div>
<button
type="button"
className="text-xs font-medium text-primary disabled:text-zinc-400"
disabled={unreadCount === 0 || markAllReadMutation.isPending}
onClick={() => markAllReadMutation.mutate()}
>
全部标为已读
</button>
</div>
<div className="max-h-[400px] overflow-y-auto">
{dropdownQuery.isLoading ? (
<div className="px-4 py-6 text-sm text-zinc-500">通知加载中...</div>
) : null}
{dropdownQuery.isError ? (
<div className="px-4 py-6 text-sm text-red-600">{resolveErrorMessage(dropdownQuery.error)}</div>
) : null}
{!dropdownQuery.isLoading && !dropdownQuery.isError ? (
dropdownQuery.data?.items?.length ? (
dropdownQuery.data.items.map((item) => (
<button
key={item.id}
type="button"
className="flex w-full items-start gap-3 border-b border-zinc-100 px-4 py-3 text-left transition hover:bg-zinc-50 disabled:opacity-60"
disabled={markReadMutation.isPending}
onClick={() => void handleNotificationClick(item)}
>
<span className="mt-1 flex w-3 justify-center">
{!item.readAt ? <span className="h-2 w-2 rounded-full bg-sky-500" /> : null}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-zinc-900">{item.title}</span>
<span className="mt-1 block text-xs text-zinc-500">
{formatNotificationRelativeTime(item.createdAt)}
</span>
</span>
</button>
))
) : (
<div className="px-4 py-6 text-sm text-zinc-500">暂无通知</div>
)
) : null}
</div>
<div className="border-t border-zinc-200 px-2 py-2">
<Button asChild variant="ghost" className="w-full justify-between" type="button">
<Link to="/notifications" onClick={() => setNotificationsOpen(false)}>
查看全部通知
</Link>
</Button>
</div>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
+75
查看文件
@@ -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");
}
+83 -29
查看文件
@@ -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,21 +90,33 @@ export function NotificationsPage() {
title="通知"
subtitle="站内通知与待办提醒。"
actions={
<>
<Button
type="button"
variant="secondary"
data-testid="notifications-mark-all-read"
disabled={(listQuery.data?.unreadCount ?? 0) === 0 || markAllReadMutation.isPending}
onClick={() => markAllReadMutation.mutate()}
>
全部标为已读
</Button>
<Button asChild variant="secondary" data-testid="notifications-back">
<Link to="/dashboard">返回仪表盘</Link>
</Button>
</>
}
/>
<div className="card-std p-6 space-y-4">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="flex flex-col gap-3 md:flex-row md:items-center">
<Tabs
data-testid="notifications-filter-tabs"
value={unreadOnly ? "unread" : "all"}
onValueChange={(value) =>
setSearchParams({
unreadOnly: value === "unread" ? "1" : "0",
page: "1",
updateFilters({
unreadOnly: value === "unread",
page: 1,
})
}
>
@@ -101,6 +130,28 @@ export function NotificationsPage() {
</TabsList>
</Tabs>
<label className="flex items-center gap-2 text-sm text-zinc-600">
<span>类型</span>
<select
data-testid="notifications-type-filter"
className="h-10 min-w-40 rounded-lg border border-zinc-200 bg-white px-3 text-sm text-zinc-700 shadow-sm outline-none transition focus:border-zinc-300 focus:ring-2 focus:ring-zinc-100"
value={selectedType}
onChange={(event) =>
updateFilters({
type: event.target.value,
page: 1,
})
}
>
{NOTIFICATION_TYPE_OPTIONS.map((option) => (
<option key={option.label} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
</div>
<div className="text-sm text-zinc-600">
未读 {listQuery.data?.unreadCount ?? 0} 条
</div>
@@ -134,7 +185,7 @@ export function NotificationsPage() {
<TableBody>
{(listQuery.data?.items ?? []).length ? (
listQuery.data?.items.map((item) => {
const targetLink = resolveTargetLink(item);
const targetLink = resolveNotificationTargetLink(item);
return (
<TableRow data-testid="notification-row" key={item.id}>
<TableCell>
@@ -189,11 +240,14 @@ export function NotificationsPage() {
<Pagination
page={page}
totalPages={totalPages}
onPageChange={(p) => setSearchParams({ unreadOnly: unreadOnly ? "1" : "0", page: String(p) })}
onPageChange={(p) =>
updateFilters({
page: p,
})
}
testIdPrefix="notifications"
/>
</div>
</div>
);
}
@@ -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 迁移,无新依赖。"
1 ID Title Description Acceptance Test_Method Tools Dev_Status Review1_Status Regression_Status Files Dependencies Notes
2 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 不影响业务。
3 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。
4 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。
5 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。
6 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 迁移,无新依赖。
7 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 迁移,无新依赖。
+31
查看文件
@@ -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',
{
+217 -1
查看文件
@@ -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();
});
});