文件
hyb-oa/client/src/pages/MobileNotificationsPage.tsx
T
2026-05-14 00:52:59 +08:00

251 行
9.7 KiB
TypeScript

import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { fetchNotifications, markAllNotificationsRead, markNotificationRead, type NotificationItem } from "../api/notifications";
import { isApiError } from "../api/types";
import { mapApiErrorMessage } from "../api/errorMessages";
import { PageHeader } from "../components/common/PageHeader";
import { Pagination } from "../components/common/Pagination";
import { PageScaffold } from "../components/patterns/PageScaffold";
import { Button } from "../components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "../components/ui/tabs";
import { resolveMobileNotificationTargetLink } from "../lib/notificationLinks";
import { resolveErrorMessage } from "../lib/resolveErrorMessage";
const PAGE_SIZE = 20;
const NOTIFICATION_TYPE_OPTIONS = [
{ label: "全部", value: "" },
{ label: "审批事件", value: "workflow.task_assigned,workflow.task_reminded,workflow.task_overdue" },
{ 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" },
];
function resolveNotificationError(error: unknown) {
if (isApiError(error)) {
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
return "加载通知失败";
}
function formatTime(value: string) {
return value.slice(0, 19).replace("T", " ");
}
function notificationTypeLabel(type: string) {
if (type.startsWith("workflow.")) return "审批事件";
if (type.startsWith("reimbursement.")) return "报销事件";
if (type.startsWith("leave.")) return "请假事件";
if (type.startsWith("purchase_request.")) return "采购事件";
if (type.startsWith("travel_request.")) return "差旅事件";
if (type.startsWith("asset.")) return "资产事件";
if (type.startsWith("inventory_check.")) return "盘点事件";
return "系统事件";
}
export function MobileNotificationsPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const currentMobileSource = `${location.pathname}${location.search}`;
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 openNotificationTarget = async (item: NotificationItem, targetLink: string | null) => {
if (!targetLink) {
toast.info("这条通知没有可直达的业务详情");
return;
}
try {
if (!item.readAt) {
await markReadMutation.mutateAsync(item.id);
}
navigate(targetLink, { state: { from: currentMobileSource } });
} catch (error) {
toast.error(resolveErrorMessage(error));
}
};
const markAllReadMutation = useMutation({
mutationFn: () => markAllNotificationsRead(),
onSuccess: async () => {
toast.success("已全部标为已读");
await queryClient.invalidateQueries({ queryKey: ["notifications"] });
},
onError: (error) => {
toast.error(resolveErrorMessage(error));
},
});
const notificationItems = listQuery.data?.items ?? [];
const totalPages = Math.max(1, Math.ceil((listQuery.data?.total ?? 0) / PAGE_SIZE));
return (
<PageScaffold className="pb-4">
<div className="mobile-page-stack" data-testid="mobile-notifications-page">
<PageHeader
title="通知"
meta={<span className="badge-neutral">未读 {listQuery.data?.unreadCount ?? 0}</span>}
actions={
<Button
type="button"
variant="secondary"
data-testid="mobile-notifications-mark-all-read"
disabled={(listQuery.data?.unreadCount ?? 0) === 0 || markAllReadMutation.isPending}
onClick={() => markAllReadMutation.mutate()}
>
全部已读
</Button>
}
/>
<section className="mobile-card mobile-page-stack" data-testid="mobile-notifications-list">
<div className="mobile-page-stack">
<Tabs
data-testid="mobile-notifications-filter-tabs"
value={unreadOnly ? "unread" : "all"}
onValueChange={(value) =>
updateFilters({
unreadOnly: value === "unread",
page: 1,
})
}
>
<TabsList className="grid h-auto w-full grid-cols-2">
<TabsTrigger data-testid="mobile-notifications-filter-all" value="all">
全部
</TabsTrigger>
<TabsTrigger data-testid="mobile-notifications-filter-unread" value="unread">
未读
</TabsTrigger>
</TabsList>
</Tabs>
<label className="mobile-field-row text-sm text-zinc-600">
<span className="shrink-0">类型</span>
<select
data-testid="mobile-notifications-type-filter"
className="h-10 min-w-0 flex-1 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>
{listQuery.isLoading ? (
<div className="mobile-empty-state">加载中...</div>
) : null}
{listQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{resolveNotificationError(listQuery.error)}
</p>
) : null}
{!listQuery.isLoading && !listQuery.isError && !notificationItems.length ? (
<div className="mobile-empty-state">暂无通知</div>
) : null}
<div className="mobile-page-stack">
{notificationItems.map((item) => {
const targetLink = resolveMobileNotificationTargetLink(item);
return (
<button
data-testid="mobile-notification-card"
key={item.id}
className="mobile-list-card w-full text-left"
type="button"
onClick={() => void openNotificationTarget(item, targetLink)}
>
<div className="mobile-list-card__header">
<div className="min-w-0">
<div className="text-xs font-medium text-primary">{notificationTypeLabel(item.type)}</div>
<div className="mobile-list-card__title mt-0.5">{item.title}</div>
{item.body ? <div className="mt-1 line-clamp-2 text-xs leading-5 text-zinc-500">{item.body}</div> : null}
</div>
<span className={item.readAt ? "badge-neutral mobile-status-slot" : "badge-warning mobile-status-slot"}>
{item.readAt ? "已读" : "未读"}
</span>
</div>
<div className="mobile-field-list mt-3">
<div className="mobile-field-row">
<div className="mobile-field-label">时间</div>
<div className="mobile-field-value">{formatTime(item.createdAt)}</div>
</div>
<div className="mobile-field-row">
<div className="mobile-field-label">去向</div>
<div className="mobile-field-value text-primary">{targetLink ? "直达详情" : "暂无直达详情"}</div>
</div>
</div>
</button>
);
})}
</div>
<Pagination
page={page}
totalPages={totalPages}
onPageChange={(nextPage) =>
updateFilters({
page: nextPage,
})
}
testIdPrefix="mobile-notifications"
/>
</section>
</div>
</PageScaffold>
);
}
export default MobileNotificationsPage;