From faa8cae4ddbdd4de8eff88f30601f90a4abe24c2 Mon Sep 17 00:00:00 2001 From: Todos Date: Wed, 28 Oct 2026 14:34:49 +0800 Subject: [PATCH 1/2] feat(web): add source badges and URL filters to notification history Filter history by channel and success through URL search params backed by the notification-history query params. Show trigger_source badges in the table, mobile cards and detail panel, and render full channel errors in the detail view. Checkpoint: LSedHhJJ_GPziIAYlRyC0 --- web/src/components/ui/select.tsx | 81 ++++++++ web/src/lib/channels.ts | 8 + web/src/locales/en.json | 15 +- web/src/locales/zh.json | 15 +- web/src/pages/history/HistoryPage.tsx | 259 +++++++++++++++++++++++--- 5 files changed, 349 insertions(+), 29 deletions(-) create mode 100644 web/src/components/ui/select.tsx diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx new file mode 100644 index 0000000..90e9f47 --- /dev/null +++ b/web/src/components/ui/select.tsx @@ -0,0 +1,81 @@ +import * as React from "react"; +import * as SelectPrimitive from "@radix-ui/react-select"; +import { Check, ChevronDown } from "lucide-react"; +import { cn } from "@/lib/utils"; + +const Select = SelectPrimitive.Root; + +const SelectValue = SelectPrimitive.Value; + +const SelectTrigger = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + span]:truncate", + className, + )} + {...props} + > + {children} + + + + +)); +SelectTrigger.displayName = SelectPrimitive.Trigger.displayName; + +const SelectContent = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ className, children, position = "popper", ...props }, ref) => ( + + + + {children} + + + +)); +SelectContent.displayName = SelectPrimitive.Content.displayName; + +const SelectItem = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +SelectItem.displayName = SelectPrimitive.Item.displayName; + +export { Select, SelectTrigger, SelectValue, SelectContent, SelectItem }; diff --git a/web/src/lib/channels.ts b/web/src/lib/channels.ts index 6c846d3..8b18961 100644 --- a/web/src/lib/channels.ts +++ b/web/src/lib/channels.ts @@ -8,3 +8,11 @@ export const CHANNELS = [ { id: "feishu", label: "Lark Bot" }, { id: "discord", label: "Discord" }, ] as const; + +/** + * Friendly label for a channel id. Unknown ids (retired channels, or names + * written by another build) fall back to the id itself so nothing is hidden. + */ +export function getChannelLabel(id: string): string { + return CHANNELS.find((channel) => channel.id === id)?.label ?? id; +} diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 3bbf390..2427e6c 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -300,7 +300,20 @@ "noContent": "No message content for this record", "emptyTitle": "No history yet", "emptyDesc": "Sent notifications will be recorded here.", - "loadError": "Failed to load history" + "loadError": "Failed to load history", + "sourceItem": "Item", + "sourceApi": "API", + "sourceTest": "Test", + "filterChannel": "Channel", + "allChannels": "All channels", + "filterAll": "All", + "filterSuccess": "Success only", + "filterFailed": "Failed only", + "filterStatus": "Filter by status", + "failureReason": "Failure reason", + "clearFilters": "Clear filters", + "emptyFilteredTitle": "No records match these filters", + "emptyFilteredDesc": "Try another channel or status." }, "admin": { "title": "Admin Panel", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 180118b..d518366 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -300,7 +300,20 @@ "noContent": "该记录无消息内容", "emptyTitle": "还没有发送记录", "emptyDesc": "通知发出后会在这里留下账目。", - "loadError": "发送记录加载失败" + "loadError": "发送记录加载失败", + "sourceItem": "事项", + "sourceApi": "API", + "sourceTest": "测试", + "filterChannel": "渠道", + "allChannels": "全部渠道", + "filterAll": "全部", + "filterSuccess": "仅成功", + "filterFailed": "仅失败", + "filterStatus": "状态筛选", + "failureReason": "失败原因", + "clearFilters": "清除筛选", + "emptyFilteredTitle": "没有符合筛选条件的记录", + "emptyFilteredDesc": "换一个渠道或状态试试。" }, "admin": { "title": "管理后台", diff --git a/web/src/pages/history/HistoryPage.tsx b/web/src/pages/history/HistoryPage.tsx index d6dbc54..4cde6b8 100644 --- a/web/src/pages/history/HistoryPage.tsx +++ b/web/src/pages/history/HistoryPage.tsx @@ -1,17 +1,49 @@ -import { Fragment, useEffect, useState, useCallback } from "react"; +import { Fragment, useCallback, useEffect, useRef, useState } from "react"; +import { useSearchParams } from "react-router"; import { useTranslation } from "react-i18next"; import { CheckCircle, XCircle, History, X, Trash2 } from "lucide-react"; import { api } from "@/lib/api"; import { ConfirmDialog } from "@/components/ConfirmDialog"; import { Skeleton, EmptyState, ErrorState } from "@/components/states"; +import { Button } from "@/components/ui/button"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { getChannelLabel } from "@/lib/channels"; import { useFocusTrap } from "@/hooks/useFocusTrap"; +import { cn } from "@/lib/utils"; import type { NotificationHistory } from "@/types"; +type StatusFilter = "all" | "true" | "false"; + +const SOURCE_LABEL_KEYS: Record = { + item: "history.sourceItem", + api: "history.sourceApi", + test: "history.sourceTest", +}; + +function SourceBadge({ source }: { source: string | null }) { + const { t } = useTranslation(); + const labelKey = source ? SOURCE_LABEL_KEYS[source] : undefined; + if (!labelKey) return null; + return ( + + {t(labelKey)} + + ); +} + interface GroupedHistory { id: string; title: string; body: string | null; item_name?: string; + trigger_source: string | null; channels: { channel: string; success: boolean; error: string | null }[]; created_at: string; allSuccess: boolean; @@ -35,6 +67,9 @@ function groupHistory(records: NotificationHistory[]): GroupedHistory[] { success: !!r.success, error: r.error, }); + if (!last.trigger_source && r.trigger_source) { + last.trigger_source = r.trigger_source; + } if (!r.success) last.allSuccess = false; } else { groups.push({ @@ -42,6 +77,7 @@ function groupHistory(records: NotificationHistory[]): GroupedHistory[] { title: r.title, body: r.body, item_name: r.item_name, + trigger_source: r.trigger_source, channels: [ { channel: r.channel, success: !!r.success, error: r.error }, ], @@ -67,37 +103,109 @@ function groupByDay(groups: GroupedHistory[]): [string, GroupedHistory[]][] { export function HistoryPage() { const { t } = useTranslation(); + const [searchParams, setSearchParams] = useSearchParams(); + + // Filter state lives in the URL so a refresh (or a shared link) keeps it. + const rawSuccess = searchParams.get("success"); + const status: StatusFilter = + rawSuccess === "true" || rawSuccess === "false" ? rawSuccess : "all"; + // `all` is the Select's sentinel, never a real channel id; treat a hand-typed + // `?channel=all` as "no channel filter" instead of querying a channel named all. + const rawChannel = searchParams.get("channel"); + const channel = rawChannel && rawChannel !== "all" ? rawChannel : ""; + const hasFilters = !!channel || status !== "all"; + const [history, setHistory] = useState([]); + const [channelOptions, setChannelOptions] = useState([]); const [loading, setLoading] = useState(true); + const [fetching, setFetching] = useState(false); const [error, setError] = useState(""); const [selected, setSelected] = useState(null); const [confirm, setConfirm] = useState<{ message: string; onConfirm: () => void; } | null>(null); + const requestIdRef = useRef(0); + const seededOptionsRef = useRef(false); const detailTrapRef = useFocusTrap(!!selected, () => setSelected(null), ); + const mergeChannelOptions = useCallback((records: NotificationHistory[]) => { + setChannelOptions((prev) => + Array.from(new Set([...prev, ...records.map((r) => r.channel)])).sort(), + ); + }, []); + const fetchHistory = useCallback(async () => { + const requestId = ++requestIdRef.current; + setFetching(true); try { + const query = new URLSearchParams({ limit: "200" }); + if (channel) query.set("channel", channel); + if (status !== "all") query.set("success", status); const data = await api.get( - "/me/notification-history?limit=200", + `/me/notification-history?${query.toString()}`, ); + if (requestId !== requestIdRef.current) return; setHistory(data); + mergeChannelOptions(data); + setError(""); } catch (e: any) { + if (requestId !== requestIdRef.current) return; setError(e.message || t("common.error")); } finally { - setLoading(false); + if (requestId === requestIdRef.current) { + setFetching(false); + setLoading(false); + } } - }, [t]); + }, [channel, status, t, mergeChannelOptions]); useEffect(() => { + // First load only: when the URL already carries a filter, the list request + // returns just the matching channels. Fetch the unfiltered set once so the + // channel dropdown can still offer every channel that appears in history. + if (!seededOptionsRef.current) { + seededOptionsRef.current = true; + if (hasFilters) { + api + .get("/me/notification-history?limit=200") + .then(mergeChannelOptions) + .catch(() => { + /* the candidate list is best-effort; the list request owns errors */ + }); + } + } fetchHistory(); - }, [fetchHistory]); + }, [fetchHistory, hasFilters, mergeChannelOptions]); + + const setFilters = (next: { channel?: string; status?: StatusFilter }) => { + const nextChannel = next.channel ?? channel; + const nextStatus = next.status ?? status; + const params = new URLSearchParams(searchParams); + if (nextChannel) params.set("channel", nextChannel); + else params.delete("channel"); + if (nextStatus !== "all") params.set("success", nextStatus); + else params.delete("success"); + setSearchParams(params, { replace: true }); + }; + + const clearFilters = () => { + const params = new URLSearchParams(searchParams); + params.delete("channel"); + params.delete("success"); + setSearchParams(params, { replace: true }); + }; + + const channelLabel = (id: string) => + t(`channels.${id}`, { defaultValue: getChannelLabel(id) }); const grouped = groupHistory(history); const groupedByDay = groupByDay(grouped); + const selectableChannels = Array.from( + new Set([...channelOptions, channel].filter(Boolean)), + ).sort((a, b) => channelLabel(a).localeCompare(channelLabel(b))); const handleClear = (e: React.MouseEvent, g: GroupedHistory) => { e.stopPropagation(); @@ -130,11 +238,63 @@ export function HistoryPage() {

{t("history.title")}

+
+
+ + {t("history.filterChannel")} + + +
+ + + setFilters({ status: value as StatusFilter }) + } + className="w-full md:w-auto" + > + + + {t("history.filterAll")} + + + {t("history.filterSuccess")} + + + {t("history.filterFailed")} + + + +
+ {error && ( { - setLoading(true); + setLoading(history.length === 0); fetchHistory(); }} retryLabel={t("common.retry")} @@ -160,13 +320,33 @@ export function HistoryPage() { )}
) : grouped.length === 0 ? ( - } - title={t("history.emptyTitle")} - description={t("history.emptyDesc")} - /> + !error && + (hasFilters ? ( + } + title={t("history.emptyFilteredTitle")} + description={t("history.emptyFilteredDesc")} + action={ + + } + /> + ) : ( + } + title={t("history.emptyTitle")} + description={t("history.emptyDesc")} + /> + )) ) : ( - <> +
{/* Desktop table */}
@@ -207,9 +387,10 @@ export function HistoryPage() { onClick={() => setSelected(g)} >
-

- {g.title} -

+
+

{g.title}

+ +
{g.item_name && (

{g.item_name} @@ -281,14 +462,17 @@ export function HistoryPage() {