feat(P19IM1-3,P19IM1-4): 接入业务事件与通知渠道后台

这个提交包含在:
2026-03-08 13:14:22 +08:00
父节点 f6d9f23553
当前提交 faff86c947
共修改 9 个文件,包含 1268 行新增和 135 行删除
+91
查看文件
@@ -0,0 +1,91 @@
import { apiRequestData } from "./http";
export type NotificationChannelType = "wecom" | "wechat_work";
export type NotificationChannelMode = "mock" | "wecom_webhook";
export type NotificationDomainScope =
| "workflow"
| "reimbursement"
| "leave"
| "procurement"
| "asset"
| "inventory";
export type NotificationChannelRouting = {
roleCodes: string[];
domainScopes: NotificationDomainScope[];
allowedTypes: string[];
};
export type NotificationChannelConfig = {
mode: NotificationChannelMode;
webhookUrl: string | null;
secret: string | null;
timeoutMs: number;
routing: NotificationChannelRouting;
};
export type NotificationChannelTemplate = {
title: string;
body: string;
footer: string;
deepLinkLabel: string;
};
export type NotificationChannel = {
id: string;
channelType: NotificationChannelType;
name: string;
enabled: boolean;
configJson: NotificationChannelConfig;
templateJson: NotificationChannelTemplate;
createdAt: string | null;
updatedAt: string | null;
};
export type NotificationChannelListResponse = {
items: NotificationChannel[];
};
export type NotificationChannelPayload = {
channelType: "wecom";
name: string;
enabled: boolean;
configJson: NotificationChannelConfig;
templateJson: NotificationChannelTemplate;
};
export type NotificationChannelTestResponse = {
channel: NotificationChannel;
testResult: {
ok: boolean;
code: string;
previewMessage: string | null;
response: unknown;
skipped: boolean;
};
};
export async function fetchNotificationChannels() {
return apiRequestData<NotificationChannelListResponse>("/api/notifications/channels");
}
export async function createNotificationChannel(payload: NotificationChannelPayload) {
return apiRequestData<{ channel: NotificationChannel }>("/api/notifications/channels", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function updateNotificationChannel(id: string, payload: Omit<NotificationChannelPayload, "channelType">) {
return apiRequestData<{ channel: NotificationChannel }>(`/api/notifications/channels/${id}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export async function testNotificationChannel(id: string) {
return apiRequestData<NotificationChannelTestResponse>(`/api/notifications/channels/${id}/test`, {
method: "POST",
body: JSON.stringify({}),
});
}
@@ -102,6 +102,12 @@ export const NAV_ITEMS: NavItem[] = [
icon: "dataset",
anyOf: ["masterdata.view", "masterdata.manage"],
},
{
to: "/system/notification-channels",
label: "通知渠道",
icon: "notifications_active",
anyOf: ["notification.channel.manage"],
},
{
to: "/system/approval-rules",
label: "审批规则",
@@ -0,0 +1,641 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { mapApiErrorMessage } from "../api/errorMessages";
import {
createNotificationChannel,
fetchNotificationChannels,
testNotificationChannel,
updateNotificationChannel,
type NotificationChannel,
type NotificationChannelConfig,
type NotificationChannelPayload,
type NotificationChannelTemplate,
} from "../api/notificationChannels";
import { isApiError } from "../api/types";
import { PageHeader } from "../components/common/PageHeader";
import { TableSkeleton } from "../components/common/TableSkeleton";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/table";
import { Textarea } from "../components/ui/textarea";
type ChannelFormState = {
channelType: "wecom";
name: string;
enabled: boolean;
mode: NotificationChannelConfig["mode"];
webhookUrl: string;
secret: string;
timeoutMs: string;
roleCodes: string[];
domainScopes: NotificationChannelConfig["routing"]["domainScopes"];
allowedTypes: string[];
title: string;
body: string;
footer: string;
deepLinkLabel: string;
};
type TestResultState = {
channelId: string;
channelName: string;
ok: boolean;
code: string;
skipped: boolean;
previewMessage: string | null;
response: unknown;
};
const ROLE_OPTIONS = [
{ value: "employee", label: "employee" },
{ value: "manager", label: "manager" },
{ value: "ceo", label: "ceo" },
{ value: "finance", label: "finance" },
{ value: "finance_mgr", label: "finance_mgr" },
{ value: "administration", label: "administration" },
{ value: "hr", label: "hr" },
{ value: "admin", label: "admin" },
] as const;
const DOMAIN_SCOPE_OPTIONS = [
{ value: "workflow", label: "审批待办" },
{ value: "reimbursement", label: "报销" },
{ value: "leave", label: "请假" },
{ value: "procurement", label: "采购" },
{ value: "asset", label: "资产" },
{ value: "inventory", label: "盘点" },
] as const;
const NOTIFICATION_TYPE_OPTIONS = [
{ value: "workflow.task_assigned", label: "workflow.task_assigned" },
{ value: "reimbursement.approved", label: "reimbursement.approved" },
{ value: "reimbursement.rejected", label: "reimbursement.rejected" },
{ value: "reimbursement.returned", label: "reimbursement.returned" },
{ value: "reimbursement.paid", label: "reimbursement.paid" },
{ value: "leave.approved", label: "leave.approved" },
{ value: "leave.rejected", label: "leave.rejected" },
{ value: "purchase_request.approved", label: "purchase_request.approved" },
{ value: "purchase_request.rejected", label: "purchase_request.rejected" },
{ value: "asset.assigned", label: "asset.assigned" },
{ value: "asset.returned", label: "asset.returned" },
{ value: "asset.transferred", label: "asset.transferred" },
{ value: "inventory_check.completed", label: "inventory_check.completed" },
] as const;
function resolveError(error: unknown) {
if (isApiError(error)) {
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
if (error instanceof Error) {
return error.message;
}
return "请求失败,请稍后重试。";
}
function buildInitialForm(): ChannelFormState {
return {
channelType: "wecom",
name: "",
enabled: true,
mode: "mock",
webhookUrl: "",
secret: "",
timeoutMs: "5000",
roleCodes: [],
domainScopes: [],
allowedTypes: [],
title: "{{title}}",
body: "{{body}}\n\n查看详情:{{detailUrl}}",
footer: "来自海音达工作台",
deepLinkLabel: "查看详情",
};
}
function mapChannelToForm(channel: NotificationChannel): ChannelFormState {
return {
channelType: "wecom",
name: channel.name,
enabled: channel.enabled,
mode: channel.configJson.mode,
webhookUrl: channel.configJson.webhookUrl ?? "",
secret: channel.configJson.secret ?? "",
timeoutMs: String(channel.configJson.timeoutMs ?? 5000),
roleCodes: channel.configJson.routing.roleCodes ?? [],
domainScopes: channel.configJson.routing.domainScopes ?? [],
allowedTypes: channel.configJson.routing.allowedTypes ?? [],
title: channel.templateJson.title,
body: channel.templateJson.body,
footer: channel.templateJson.footer,
deepLinkLabel: channel.templateJson.deepLinkLabel,
};
}
function toggleSelection(values: string[], value: string) {
return values.includes(value) ? values.filter((item) => item !== value) : [...values, value];
}
function formatDateTime(value: string | null) {
if (!value) return "-";
return value.slice(0, 19).replace("T", " ");
}
function formatChannelType(channelType: string) {
return channelType === "wechat_work" ? "企微(兼容别名)" : "企微";
}
function formatMode(mode: string) {
return mode === "wecom_webhook" ? "Webhook" : "Mock";
}
function formatSummary(values: string[], labelMap: Record<string, string>, emptyLabel: string) {
if (!values.length) return emptyLabel;
return values.map((value) => labelMap[value] ?? value).join("、");
}
function buildPayload(form: ChannelFormState): NotificationChannelPayload {
const templateJson: NotificationChannelTemplate = {
title: form.title.trim() || "{{title}}",
body: form.body.trim() || "{{body}}\n\n查看详情:{{detailUrl}}",
footer: form.footer.trim() || "来自海音达工作台",
deepLinkLabel: form.deepLinkLabel.trim() || "查看详情",
};
return {
channelType: form.channelType,
name: form.name.trim(),
enabled: form.enabled,
configJson: {
mode: form.mode,
webhookUrl: form.webhookUrl.trim() || null,
secret: form.secret.trim() || null,
timeoutMs: Math.max(100, Number(form.timeoutMs || 5000)),
routing: {
roleCodes: form.roleCodes,
domainScopes: form.domainScopes,
allowedTypes: form.allowedTypes,
},
},
templateJson,
};
}
const roleLabelMap = Object.fromEntries(ROLE_OPTIONS.map((item) => [item.value, item.label]));
const domainLabelMap = Object.fromEntries(DOMAIN_SCOPE_OPTIONS.map((item) => [item.value, item.label]));
export function NotificationChannelsPage() {
const queryClient = useQueryClient();
const [error, setError] = useState("");
const [editingId, setEditingId] = useState<string | null>(null);
const [form, setForm] = useState<ChannelFormState>(buildInitialForm);
const [lastTestResult, setLastTestResult] = useState<TestResultState | null>(null);
const channelsQuery = useQuery({
queryKey: ["notification-channels"],
queryFn: () => fetchNotificationChannels(),
});
const saveMutation = useMutation({
mutationFn: async () => {
if (editingId) {
const payload = buildPayload(form);
return updateNotificationChannel(editingId, {
name: payload.name,
enabled: payload.enabled,
configJson: payload.configJson,
templateJson: payload.templateJson,
});
}
return createNotificationChannel(buildPayload(form));
},
onSuccess: async ({ channel }) => {
await queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
setEditingId(channel.id);
setForm(mapChannelToForm(channel));
setError("");
toast.success(editingId ? "通知渠道已更新" : "通知渠道已创建");
},
onError: (mutationError) => {
const message = resolveError(mutationError);
setError(message);
toast.error(message);
},
});
const testMutation = useMutation({
mutationFn: async (channel: NotificationChannel) => {
const result = await testNotificationChannel(channel.id);
return {
channelName: channel.name,
...result,
};
},
onSuccess: (result) => {
setLastTestResult({
channelId: result.channel.id,
channelName: result.channelName,
ok: result.testResult.ok,
code: result.testResult.code,
skipped: result.testResult.skipped,
previewMessage: result.testResult.previewMessage,
response: result.testResult.response,
});
if (result.testResult.ok) {
toast.success("测试发送成功");
} else {
toast.error(`测试发送失败:${result.testResult.code}`);
}
},
onError: (mutationError) => {
const message = resolveError(mutationError);
setError(message);
toast.error(message);
},
});
function startCreate() {
setEditingId(null);
setForm(buildInitialForm());
setLastTestResult(null);
setError("");
}
function startEdit(channel: NotificationChannel) {
setEditingId(channel.id);
setForm(mapChannelToForm(channel));
setError("");
}
const channels = channelsQuery.data?.items ?? [];
return (
<div className="space-y-6">
<PageHeader
title="通知渠道"
subtitle="维护企微群机器人渠道、业务域路由与测试发送。IM 继续通过 Outbox 异步派发。"
actions={
<Button type="button" variant="secondary" onClick={startCreate} data-testid="notification-channels-create">
新建渠道
</Button>
}
/>
{error ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>
) : null}
<div className="card-std space-y-4 p-6">
<div className="flex items-center justify-between gap-3">
<h3 className="text-base font-semibold text-zinc-900">渠道列表</h3>
<p className="text-sm text-zinc-500">当前共 {channels.length} 条渠道配置</p>
</div>
{channelsQuery.isLoading ? <TableSkeleton columns={8} rows={4} /> : null}
{channelsQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{resolveError(channelsQuery.error)}
</p>
) : null}
{!channelsQuery.isLoading && !channelsQuery.isError ? (
<div className="rounded-lg border border-zinc-200">
<Table data-testid="notification-channels-table">
<TableHeader>
<tr>
<TableHead>名称</TableHead>
<TableHead>类型</TableHead>
<TableHead>模式</TableHead>
<TableHead>启用状态</TableHead>
<TableHead>业务域</TableHead>
<TableHead>通知类型数</TableHead>
<TableHead>角色范围</TableHead>
<TableHead>最近更新时间</TableHead>
<TableHead className="w-40">操作</TableHead>
</tr>
</TableHeader>
<TableBody>
{channels.length ? (
channels.map((channel) => (
<TableRow key={channel.id} data-testid="notification-channel-row">
<TableCell className="font-medium text-zinc-900">{channel.name}</TableCell>
<TableCell>{formatChannelType(channel.channelType)}</TableCell>
<TableCell>{formatMode(channel.configJson.mode)}</TableCell>
<TableCell>{channel.enabled ? "启用" : "停用"}</TableCell>
<TableCell className="max-w-xs text-xs text-zinc-600">
{formatSummary(channel.configJson.routing.domainScopes, domainLabelMap, "全部业务域")}
</TableCell>
<TableCell>{channel.configJson.routing.allowedTypes.length || "全部"}</TableCell>
<TableCell className="max-w-xs text-xs text-zinc-600">
{formatSummary(channel.configJson.routing.roleCodes, roleLabelMap, "全部角色")}
</TableCell>
<TableCell className="text-xs text-zinc-600">{formatDateTime(channel.updatedAt)}</TableCell>
<TableCell>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => startEdit(channel)}
data-testid="notification-channel-edit"
>
编辑
</Button>
<Button
type="button"
size="sm"
variant="secondary"
disabled={testMutation.isPending}
onClick={() => testMutation.mutate(channel)}
data-testid="notification-channel-test"
>
测试
</Button>
</div>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={9} className="py-4 text-center text-sm text-zinc-500">
暂无通知渠道,请先创建企微渠道。
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
) : null}
</div>
<div className="grid gap-6 xl:grid-cols-[minmax(0,2fr)_minmax(320px,1fr)]">
<div className="card-std space-y-4 p-6">
<div className="flex items-center justify-between gap-3">
<div>
<h3 className="text-base font-semibold text-zinc-900">
{editingId ? "编辑通知渠道" : "新建通知渠道"}
</h3>
<p className="text-sm text-zinc-500">
通过角色 / 业务域 / 通知类型三维控制 IM 群路由,避免默认全量广播。
</p>
</div>
{editingId ? (
<Button type="button" variant="outline" onClick={startCreate}>
切换到新建
</Button>
) : null}
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="channelType">渠道类型</Label>
<select
id="channelType"
className="select-std"
value={form.channelType}
disabled={Boolean(editingId)}
onChange={(event) => setForm((prev) => ({ ...prev, channelType: event.target.value as "wecom" }))}
>
<option value="wecom">企微群机器人</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="channelName">渠道名称</Label>
<Input
id="channelName"
value={form.name}
placeholder="采购经理群"
onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="channelMode">模式</Label>
<select
id="channelMode"
className="select-std"
value={form.mode}
onChange={(event) =>
setForm((prev) => ({
...prev,
mode: event.target.value as NotificationChannelConfig["mode"],
}))
}
>
<option value="mock">Mock</option>
<option value="wecom_webhook">企微 Webhook</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="timeoutMs">超时(毫秒)</Label>
<Input
id="timeoutMs"
type="number"
min={100}
value={form.timeoutMs}
onChange={(event) => setForm((prev) => ({ ...prev, timeoutMs: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="webhookUrl">Webhook URL</Label>
<Input
id="webhookUrl"
value={form.webhookUrl}
placeholder={form.mode === "mock" ? "Mock 模式可留空" : "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?..."}
onChange={(event) => setForm((prev) => ({ ...prev, webhookUrl: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="webhookSecret">Webhook Secret(可空)</Label>
<Input
id="webhookSecret"
value={form.secret}
placeholder="可选,配置后将参与签名"
onChange={(event) => setForm((prev) => ({ ...prev, secret: event.target.value }))}
/>
</div>
</div>
<label className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.enabled}
onChange={(event) => setForm((prev) => ({ ...prev, enabled: event.target.checked }))}
/>
启用该渠道
</label>
<div className="grid gap-4 lg:grid-cols-3">
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">角色范围</h4>
<p className="text-xs text-zinc-500">留空表示不限角色。</p>
</div>
<div className="space-y-2">
{ROLE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.roleCodes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
roleCodes: toggleSelection(prev.roleCodes, option.value),
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">业务域</h4>
<p className="text-xs text-zinc-500">留空表示不限业务域。</p>
</div>
<div className="space-y-2">
{DOMAIN_SCOPE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.domainScopes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
domainScopes: toggleSelection(prev.domainScopes, option.value) as ChannelFormState["domainScopes"],
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">通知类型</h4>
<p className="text-xs text-zinc-500">留空表示消费所有 IM 一期支持类型。</p>
</div>
<div className="max-h-72 space-y-2 overflow-auto pr-1">
{NOTIFICATION_TYPE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.allowedTypes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
allowedTypes: toggleSelection(prev.allowedTypes, option.value),
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="templateTitle">标题模板</Label>
<Input
id="templateTitle"
value={form.title}
onChange={(event) => setForm((prev) => ({ ...prev, title: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="templateFooter">页脚模板</Label>
<Input
id="templateFooter"
value={form.footer}
onChange={(event) => setForm((prev) => ({ ...prev, footer: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="templateBody">正文模板</Label>
<Textarea
id="templateBody"
value={form.body}
onChange={(event) => setForm((prev) => ({ ...prev, body: event.target.value }))}
/>
<p className="text-xs text-zinc-500">一期支持变量:title、body、detailUrl、targetType、targetId、footer。</p>
</div>
</div>
<div className="flex flex-wrap gap-3">
<Button
type="button"
onClick={() => saveMutation.mutate()}
disabled={saveMutation.isPending}
data-testid="notification-channel-save"
>
{editingId ? "保存更新" : "创建渠道"}
</Button>
<Button type="button" variant="secondary" onClick={startCreate} disabled={saveMutation.isPending}>
重置表单
</Button>
</div>
</div>
<div className="card-std space-y-4 p-6">
<div>
<h3 className="text-base font-semibold text-zinc-900">测试发送</h3>
<p className="text-sm text-zinc-500">仅对已保存渠道执行同步测试,不写业务 Outbox。</p>
</div>
{lastTestResult ? (
<div className="space-y-3 rounded-lg border border-zinc-200 bg-zinc-50 p-4 text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-zinc-900">渠道:</span>
<span>{lastTestResult.channelName}</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-zinc-900">结果:</span>
<span className={lastTestResult.ok ? "text-emerald-600" : "text-red-600"}>
{lastTestResult.ok ? "成功" : "失败"}
</span>
<span className="text-zinc-500">code={lastTestResult.code}</span>
{lastTestResult.skipped ? <span className="text-amber-600">(已跳过)</span> : null}
</div>
<div>
<p className="mb-1 font-medium text-zinc-900">预览消息</p>
<pre className="whitespace-pre-wrap rounded-lg bg-white p-3 text-xs text-zinc-700">
{lastTestResult.previewMessage ?? "<empty>"}
</pre>
</div>
<div>
<p className="mb-1 font-medium text-zinc-900">Provider 响应</p>
<pre className="overflow-auto rounded-lg bg-white p-3 text-xs text-zinc-700">
{JSON.stringify(lastTestResult.response ?? null, null, 2)}
</pre>
</div>
</div>
) : (
<p className="rounded-lg border border-dashed border-zinc-200 px-3 py-4 text-sm text-zinc-500">
从列表中选择一条渠道并点击“测试”,即可查看发送结果与消息预览。
</p>
)}
</div>
</div>
</div>
);
}
+10
查看文件
@@ -17,6 +17,7 @@ import { InvoicePoolPage } from "../pages/InvoicePoolPage";
import { LoginPage } from "../pages/LoginPage";
import { LeaveRequestPage } from "../pages/LeaveRequestPage";
import { NotificationsPage } from "../pages/NotificationsPage";
import { NotificationChannelsPage } from "../pages/NotificationChannelsPage";
import { PurchaseRequestsPage } from "../pages/PurchaseRequestsPage";
import { AssetRegistryPage } from "../pages/AssetRegistryPage";
import { InventoryChecksPage } from "../pages/InventoryChecksPage";
@@ -220,6 +221,15 @@ export function AppRouter() {
}
/>
<Route
path="system/notification-channels"
element={
<RequirePermission anyOf={["notification.channel.manage"]}>
<NotificationChannelsPage />
</RequirePermission>
}
/>
<Route
path="system/approval-rules"
element={