ceshi
This commit is contained in:
1 parent
1ffead7ee2
commit
5f11926db5
14 files changed
+2031
-94
No files matched your search
@@ -0,0 +1,338 @@
|
||||
/**
|
||||
* 通知模板管理 API 客户端 + React Query hooks。
|
||||
*
|
||||
* 后端:`/api/notification-templates`(见 app/gateway/routers/notification_templates.py)。
|
||||
* 全局共享;读/写均仅 admin。snake_case ⇄ camelCase 在此边界收敛。
|
||||
*/
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
|
||||
export const NOTIFICATION_TEMPLATE_VARIABLES = [
|
||||
"userName",
|
||||
"taskName",
|
||||
"taskId",
|
||||
"dueDate",
|
||||
] as const;
|
||||
|
||||
export type NotificationTemplateVariable =
|
||||
(typeof NOTIFICATION_TEMPLATE_VARIABLES)[number];
|
||||
|
||||
export interface NotificationTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
titleTemplate: string;
|
||||
contentTemplate: string;
|
||||
tags: string[];
|
||||
enabled: boolean;
|
||||
version: number;
|
||||
createdBy: string | null;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationTemplateInput {
|
||||
name: string;
|
||||
titleTemplate: string;
|
||||
contentTemplate: string;
|
||||
tags: string[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationTemplateUpdateInput extends NotificationTemplateInput {
|
||||
expectedVersion: number;
|
||||
}
|
||||
|
||||
export interface ListNotificationTemplatesParams {
|
||||
keyword?: string;
|
||||
enabled?: boolean | null;
|
||||
tag?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface NotificationTemplateListResult {
|
||||
items: NotificationTemplate[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface PreviewResult {
|
||||
title: string;
|
||||
content: string;
|
||||
missingVariables: string[];
|
||||
}
|
||||
|
||||
/** 409 乐观锁冲突:携带服务端最新完整记录。 */
|
||||
export class NotificationTemplateConflictError extends Error {
|
||||
readonly server: NotificationTemplate;
|
||||
|
||||
constructor(server: NotificationTemplate, message = "版本冲突") {
|
||||
super(message);
|
||||
this.name = "NotificationTemplateConflictError";
|
||||
this.server = server;
|
||||
}
|
||||
}
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/notification-templates`;
|
||||
|
||||
interface ServerTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
title_template: string;
|
||||
content_template: string;
|
||||
tags: string[];
|
||||
enabled: boolean;
|
||||
version: number;
|
||||
created_by?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
function toTemplate(s: ServerTemplate): NotificationTemplate {
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
titleTemplate: s.title_template,
|
||||
contentTemplate: s.content_template,
|
||||
tags: s.tags ?? [],
|
||||
enabled: s.enabled ?? true,
|
||||
version: s.version ?? 1,
|
||||
createdBy: s.created_by ?? null,
|
||||
createdAt: s.created_at ?? null,
|
||||
updatedAt: s.updated_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toBody(input: NotificationTemplateInput & { expectedVersion?: number }) {
|
||||
const body: Record<string, unknown> = {
|
||||
name: input.name,
|
||||
title_template: input.titleTemplate,
|
||||
content_template: input.contentTemplate,
|
||||
tags: input.tags,
|
||||
enabled: input.enabled,
|
||||
};
|
||||
if (input.expectedVersion !== undefined) {
|
||||
body.expected_version = input.expectedVersion;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function detailMessage(data: unknown, fallback: string): string {
|
||||
if (!data || typeof data !== "object" || !("detail" in data)) return fallback;
|
||||
const detail = (data as { detail: unknown }).detail;
|
||||
if (typeof detail === "string") return detail;
|
||||
if (detail && typeof detail === "object" && "message" in detail) {
|
||||
const msg = (detail as { message: unknown }).message;
|
||||
if (typeof msg === "string") return msg;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
if (res.status === 204) return undefined as T;
|
||||
const data = await res.json().catch(() => null as unknown);
|
||||
if (!res.ok) {
|
||||
if (res.status === 409 && data && typeof data === "object" && "detail" in data) {
|
||||
const detail = (data as { detail: unknown }).detail;
|
||||
if (detail && typeof detail === "object" && "server" in detail) {
|
||||
const server = (detail as { server: ServerTemplate }).server;
|
||||
if (server && typeof server === "object" && "id" in server) {
|
||||
throw new NotificationTemplateConflictError(
|
||||
toTemplate(server),
|
||||
detailMessage(data, "版本冲突"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(detailMessage(data, `${ctx} failed (${res.status})`));
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export async function listNotificationTemplates(
|
||||
params: ListNotificationTemplatesParams = {},
|
||||
): Promise<NotificationTemplateListResult> {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.keyword) qs.set("keyword", params.keyword);
|
||||
if (params.enabled === true || params.enabled === false) {
|
||||
qs.set("enabled", String(params.enabled));
|
||||
}
|
||||
if (params.tag) qs.set("tag", params.tag);
|
||||
if (params.page) qs.set("page", String(params.page));
|
||||
if (params.pageSize) qs.set("page_size", String(params.pageSize));
|
||||
const query = qs.toString();
|
||||
const res = await apiFetch(`${BASE()}${query ? `?${query}` : ""}`, { method: "GET" });
|
||||
const data = await readJson<{
|
||||
items: ServerTemplate[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}>(res, "list notification templates");
|
||||
const result: NotificationTemplateListResult = {
|
||||
items: (data.items ?? []).map(toTemplate),
|
||||
total: data.total ?? 0,
|
||||
page: data.page ?? 1,
|
||||
pageSize: data.page_size ?? params.pageSize ?? 20,
|
||||
};
|
||||
writeYLog({
|
||||
optType: OptType.search,
|
||||
optDetail: "CM助手-全量-通知模板-列表",
|
||||
url: `${BASE()}${query ? `?${query}` : ""}`,
|
||||
reqParam: params,
|
||||
returnParam: { total: result.total, page: result.page },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function getNotificationTemplate(id: string): Promise<NotificationTemplate> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
|
||||
const tpl = toTemplate(await readJson<ServerTemplate>(res, "get notification template"));
|
||||
writeYLog({
|
||||
optType: OptType.view,
|
||||
optDetail: "CM助手-全量-通知模板-查看",
|
||||
url: `${BASE()}/${encodeURIComponent(id)}`,
|
||||
reqParam: { id },
|
||||
returnParam: tpl,
|
||||
});
|
||||
return tpl;
|
||||
}
|
||||
|
||||
export async function createNotificationTemplate(
|
||||
input: NotificationTemplateInput,
|
||||
): Promise<NotificationTemplate> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(toBody(input)),
|
||||
});
|
||||
const tpl = toTemplate(await readJson<ServerTemplate>(res, "create notification template"));
|
||||
writeYLog({
|
||||
optType: OptType.create,
|
||||
optDetail: "CM助手-全量-通知模板-创建",
|
||||
url: BASE(),
|
||||
reqParam: input,
|
||||
returnParam: tpl,
|
||||
});
|
||||
return tpl;
|
||||
}
|
||||
|
||||
export async function updateNotificationTemplate(
|
||||
id: string,
|
||||
input: NotificationTemplateUpdateInput,
|
||||
): Promise<NotificationTemplate> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(toBody(input)),
|
||||
});
|
||||
const tpl = toTemplate(await readJson<ServerTemplate>(res, "update notification template"));
|
||||
writeYLog({
|
||||
optType: OptType.edit,
|
||||
optDetail: "CM助手-全量-通知模板-修改",
|
||||
url: `${BASE()}/${encodeURIComponent(id)}`,
|
||||
reqParam: { id, input },
|
||||
returnParam: tpl,
|
||||
});
|
||||
return tpl;
|
||||
}
|
||||
|
||||
export async function deleteNotificationTemplate(id: string): Promise<void> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
await readJson<void>(res, "delete notification template");
|
||||
writeYLog({
|
||||
optType: OptType.delete,
|
||||
optDetail: "CM助手-全量-通知模板-删除",
|
||||
url: `${BASE()}/${encodeURIComponent(id)}`,
|
||||
reqParam: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function duplicateNotificationTemplate(
|
||||
id: string,
|
||||
): Promise<NotificationTemplate> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}/duplicate`, {
|
||||
method: "POST",
|
||||
});
|
||||
const tpl = toTemplate(await readJson<ServerTemplate>(res, "duplicate notification template"));
|
||||
writeYLog({
|
||||
optType: OptType.create,
|
||||
optDetail: "CM助手-全量-通知模板-复制",
|
||||
url: `${BASE()}/${encodeURIComponent(id)}/duplicate`,
|
||||
reqParam: { id },
|
||||
returnParam: tpl,
|
||||
});
|
||||
return tpl;
|
||||
}
|
||||
|
||||
export async function previewNotificationTemplate(input: {
|
||||
titleTemplate: string;
|
||||
contentTemplate: string;
|
||||
variables: Record<string, string>;
|
||||
}): Promise<PreviewResult> {
|
||||
const res = await apiFetch(`${BASE()}/preview`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title_template: input.titleTemplate,
|
||||
content_template: input.contentTemplate,
|
||||
variables: input.variables,
|
||||
}),
|
||||
});
|
||||
const data = await readJson<{
|
||||
title: string;
|
||||
content: string;
|
||||
missing_variables: string[];
|
||||
}>(res, "preview notification template");
|
||||
return {
|
||||
title: data.title,
|
||||
content: data.content,
|
||||
missingVariables: data.missing_variables ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
const KEY = "notification-templates";
|
||||
|
||||
export function useNotificationTemplates(params: ListNotificationTemplatesParams) {
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
KEY,
|
||||
"list",
|
||||
params.keyword ?? "",
|
||||
params.enabled === true ? "1" : params.enabled === false ? "0" : "",
|
||||
params.tag ?? "",
|
||||
params.page ?? 1,
|
||||
params.pageSize ?? 20,
|
||||
],
|
||||
queryFn: () => listNotificationTemplates(params),
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useNotificationTemplateActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey: [KEY] });
|
||||
return {
|
||||
create: useMutation({ mutationFn: createNotificationTemplate, onSuccess: invalidate }),
|
||||
update: useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: NotificationTemplateUpdateInput }) =>
|
||||
updateNotificationTemplate(id, input),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
remove: useMutation({ mutationFn: deleteNotificationTemplate, onSuccess: invalidate }),
|
||||
duplicate: useMutation({
|
||||
mutationFn: duplicateNotificationTemplate,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user