文件
hyb-oa/client/src/pages/NotificationsPage.tsx
T

300 行
12 KiB
TypeScript

import { Link, useSearchParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
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,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "../components/ui/tabs";
const PAGE_SIZE = 20;
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();
const [searchParams, setSearchParams] = useSearchParams();
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, selectedType, page],
queryFn: () =>
fetchNotifications({
unreadOnly,
page,
pageSize: PAGE_SIZE,
...(selectedType ? { type: selectedType } : {}),
}),
});
const markReadMutation = useMutation({
mutationFn: async (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 totalPages = Math.max(1, Math.ceil((listQuery.data?.total ?? 0) / PAGE_SIZE));
const notificationItems = listQuery.data?.items ?? [];
return (
<div className="space-y-6">
<PageHeader
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) =>
updateFilters({
unreadOnly: value === "unread",
page: 1,
})
}
>
<TabsList className="flex w-full flex-wrap justify-start gap-1 md:w-auto">
<TabsTrigger data-testid="notifications-filter-all" value="all">
全部
</TabsTrigger>
<TabsTrigger data-testid="notifications-filter-unread" value="unread">
未读
</TabsTrigger>
</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>
</div>
{listQuery.isLoading ? <TableSkeleton columns={4} rows={5} /> : null}
{listQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{isApiError(listQuery.error)
? `${listQuery.error.code}: ${mapApiErrorMessage(
listQuery.error.code,
listQuery.error.details,
listQuery.error.message,
)}`
: "加载通知失败"}
</p>
) : null}
{!listQuery.isLoading && !listQuery.isError ? (
<>
<div className="space-y-3 md:hidden">
{notificationItems.length ? (
notificationItems.map((item) => {
const targetLink = resolveNotificationTargetLink(item);
return (
<div data-testid="notification-mobile-card" key={item.id} className="rounded-lg border border-zinc-200 bg-white p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-sm font-semibold text-zinc-900">{item.title}</div>
{item.body ? <div className="mt-1 text-xs leading-5 text-zinc-500">{item.body}</div> : null}
</div>
<span className="shrink-0 rounded-full bg-zinc-100 px-2 py-1 text-xs text-zinc-600">
{item.readAt ? "已读" : "未读"}
</span>
</div>
<div className="mt-3 text-xs text-zinc-500">{item.createdAt.slice(0, 19).replace("T", " ")}</div>
<div className="mt-3 flex flex-wrap gap-2">
{targetLink ? (
<Button asChild size="sm" variant="secondary" data-testid="notification-mobile-target-link">
<Link to={targetLink}>查看</Link>
</Button>
) : null}
{!item.readAt ? (
<Button
data-testid="notification-mobile-mark-read"
size="sm"
type="button"
variant="secondary"
disabled={markReadMutation.isPending}
onClick={() => markReadMutation.mutate(item.id)}
>
标为已读
</Button>
) : null}
</div>
</div>
);
})
) : (
<div className="rounded-lg border border-zinc-200 p-4 text-sm text-zinc-500">暂无通知</div>
)}
</div>
<div className="hidden rounded-lg border border-zinc-200 md:block">
<Table data-testid="notifications-table">
<TableHeader>
<tr>
<TableHead>标题</TableHead>
<TableHead>时间</TableHead>
<TableHead>状态</TableHead>
<TableHead className="w-40">操作</TableHead>
</tr>
</TableHeader>
<TableBody>
{notificationItems.length ? (
notificationItems.map((item) => {
const targetLink = resolveNotificationTargetLink(item);
return (
<TableRow data-testid="notification-row" key={item.id}>
<TableCell>
<div className="font-medium text-zinc-900">{item.title}</div>
{item.body ? (
<div className="mt-1 text-xs text-zinc-500">{item.body}</div>
) : null}
</TableCell>
<TableCell className="text-xs text-zinc-600">
{item.createdAt.slice(0, 19).replace("T", " ")}
</TableCell>
<TableCell className="text-xs text-zinc-600">
{item.readAt ? "已读" : "未读"}
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-2">
{targetLink ? (
<Button asChild size="sm" variant="secondary" data-testid="notification-target-link">
<Link to={targetLink}>查看</Link>
</Button>
) : null}
{!item.readAt ? (
<Button
data-testid="notification-mark-read"
size="sm"
type="button"
variant="secondary"
disabled={markReadMutation.isPending}
onClick={() => markReadMutation.mutate(item.id)}
>
标为已读
</Button>
) : null}
</div>
</TableCell>
</TableRow>
);
})
) : (
<TableRow>
<TableCell className="py-3 text-zinc-500" colSpan={4}>
暂无通知
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</>
) : null}
<Pagination
page={page}
totalPages={totalPages}
onPageChange={(p) =>
updateFilters({
page: p,
})
}
testIdPrefix="notifications"
/>
</div>
</div>
);
}