init: 初始化项目

This commit is contained in:
zwt13703
2026-07-08 20:02:29 +08:00
parent 22590ae7b8
commit 1bb84df4ca
98 changed files with 8535 additions and 2 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
.git
*.local
public/tinymce/
+25
View File
@@ -0,0 +1,25 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
public/tinymce
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+18
View File
@@ -0,0 +1,18 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run postinstall && npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+26
View File
@@ -0,0 +1,26 @@
server {
listen 80;
server_name _;
client_max_body_size 100M;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
}
location / {
try_files $uri $uri/ /index.html;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_min_length 1000;
}
+2773
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"postinstall": "cp -r node_modules/tinymce public/tinymce 2>/dev/null || true"
},
"dependencies": {
"@ant-design/icons": "^6.3.2",
"@tinymce/tinymce-react": "^6.3.0",
"antd": "^6.5.0",
"axios": "^1.18.1",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1",
"tinymce": "^8.7.0"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3",
"oxlint": "^1.71.0",
"typescript": "~6.0.2",
"vite": "^8.1.1"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+26
View File
@@ -0,0 +1,26 @@
import { Routes, Route } from "react-router-dom";
import AppLayout from "./components/AppLayout";
import TemplateList from "./pages/TemplateList";
import TemplateEditor from "./pages/TemplateEditor";
import ModelList from "./pages/ModelList";
import TaskList from "./pages/TaskList";
import TaskDetail from "./pages/TaskDetail";
import Settings from "./pages/Settings";
function App() {
return (
<Routes>
<Route element={<AppLayout />}>
<Route path="/" element={<TemplateList />} />
<Route path="/templates" element={<TemplateList />} />
<Route path="/editor/:id" element={<TemplateEditor />} />
<Route path="/models" element={<ModelList />} />
<Route path="/tasks" element={<TaskList />} />
<Route path="/tasks/:id" element={<TaskDetail />} />
<Route path="/settings" element={<Settings />} />
</Route>
</Routes>
);
}
export default App;
+57
View File
@@ -0,0 +1,57 @@
import request from "./request";
import type { GenerationPoint } from "../types";
export async function listGenerationPoints(template_id: string) {
const { data } = await request.get<GenerationPoint[]>("/generation-points", {
params: { template_id },
});
return data;
}
export async function createGenerationPoint(body: {
template_id: string;
position: string;
prompt: string;
model_id?: string;
order?: number;
selected_text?: string;
need_ref_file?: boolean;
remark?: string;
ref_file?: File;
}) {
const formData = new FormData();
formData.append("template_id", body.template_id);
formData.append("position", body.position);
formData.append("prompt", body.prompt);
if (body.model_id) formData.append("model_id", body.model_id);
if (body.order !== undefined) formData.append("order", String(body.order));
if (body.selected_text) formData.append("selected_text", body.selected_text);
if (body.need_ref_file) formData.append("need_ref_file", "true");
if (body.remark) formData.append("remark", body.remark);
if (body.ref_file) formData.append("ref_file", body.ref_file);
const { data } = await request.post<GenerationPoint>("/generation-points", formData);
return data;
}
export async function updateGenerationPoint(
id: string,
body: Partial<GenerationPoint>
) {
const { data } = await request.put<GenerationPoint>(`/generation-points/${id}`, body);
return data;
}
export async function deleteGenerationPoint(id: string) {
await request.delete(`/generation-points/${id}`);
}
export async function batchUpdateOrder(points: { id: string; order: number }[]) {
await request.post("/generation-points/batch-order", { points });
}
export async function testGenerationPoint(pointId: string) {
const { data } = await request.post<{ result: string }>(
`/generation-points/${pointId}/test`
);
return data.result;
}
+36
View File
@@ -0,0 +1,36 @@
import request from "./request";
import type { AIModel } from "../types";
export async function listModels(params?: { enabled?: boolean }) {
const { data } = await request.get<AIModel[]>("/models", { params });
return data;
}
export async function getModel(id: string) {
const { data } = await request.get<AIModel>(`/models/${id}`);
return data;
}
export async function createModel(body: Partial<AIModel> & { api_key: string }) {
const { data } = await request.post<AIModel>("/models", body);
return data;
}
export async function updateModel(id: string, body: Partial<AIModel>) {
const { data } = await request.put<AIModel>(`/models/${id}`, body);
return data;
}
export async function deleteModel(id: string) {
await request.delete(`/models/${id}`);
}
export async function toggleModel(id: string, is_enabled: boolean) {
const { data } = await request.patch<AIModel>(`/models/${id}/toggle`, { is_enabled });
return data;
}
export async function testModel(id: string) {
const { data } = await request.post<{ success: boolean; result?: string; error?: string }>(`/models/${id}/test`);
return data;
}
+16
View File
@@ -0,0 +1,16 @@
import axios from "axios";
const request = axios.create({
baseURL: "/api/v1",
timeout: 30000,
});
request.interceptors.response.use(
(response) => response,
(error) => {
const message = error.response?.data?.detail || error.message || "请求失败";
return Promise.reject(new Error(message));
}
);
export default request;
+10
View File
@@ -0,0 +1,10 @@
import request from "./request";
export async function getAllSettings() {
const { data } = await request.get<Record<string, string>>("/settings");
return data;
}
export async function updateSetting(key: string, value: string, description?: string) {
await request.put(`/settings/${key}`, { value, description });
}
+27
View File
@@ -0,0 +1,27 @@
import request from "./request";
import type { GenerationTask } from "../types";
export async function triggerGeneration(templateId: string) {
const { data } = await request.post<{ task_id: string; status: string }>(
`/templates/${templateId}/generate`
);
return data;
}
export async function getTaskStatus(taskId: string) {
const { data } = await request.get<GenerationTask>(`/tasks/${taskId}`);
return data;
}
export async function listTasks() {
const { data } = await request.get<GenerationTask[]>("/tasks");
return data;
}
export async function cancelTask(taskId: string) {
await request.post(`/tasks/${taskId}/cancel`);
}
export function getTaskDownloadUrl(taskId: string, format: "docx" | "pdf" = "docx") {
return `/api/v1/tasks/${taskId}/download?format=${format}`;
}
+37
View File
@@ -0,0 +1,37 @@
import request from "./request";
import type { Template, TemplateListItem } from "../types";
export async function listTemplates() {
const { data } = await request.get<TemplateListItem[]>("/templates");
return data;
}
export async function getTemplate(id: string) {
const { data } = await request.get<Template>(`/templates/${id}`);
return data;
}
export async function uploadTemplate(file: File, name?: string) {
const formData = new FormData();
formData.append("file", file);
if (name) formData.append("name", name);
const { data } = await request.post<Template>("/templates", formData);
return data;
}
export async function getTemplateHtml(id: string) {
const { data } = await request.get<{ html_content: string }>(`/templates/${id}/html`);
return data.html_content;
}
export async function updateTemplateHtml(id: string, html_content: string) {
await request.put(`/templates/${id}/html`, { html_content });
}
export async function deleteTemplate(id: string) {
await request.delete(`/templates/${id}`);
}
export function getDownloadUrl(id: string, format: "docx" | "pdf" = "docx") {
return `/api/v1/templates/${id}/download?format=${format}`;
}
+57
View File
@@ -0,0 +1,57 @@
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import { Layout, Menu } from "antd";
import {
FileTextOutlined,
RobotOutlined,
UnorderedListOutlined,
SettingOutlined,
} from "@ant-design/icons";
const { Sider, Content, Header } = Layout;
const menuItems = [
{ key: "/templates", icon: <FileTextOutlined />, label: "模板管理" },
{ key: "/models", icon: <RobotOutlined />, label: "模型管理" },
{ key: "/tasks", icon: <UnorderedListOutlined />, label: "任务历史" },
{ key: "/settings", icon: <SettingOutlined />, label: "系统设置" },
];
export default function AppLayout() {
const navigate = useNavigate();
const location = useLocation();
const selectedKey = "/" + location.pathname.split("/")[1];
return (
<Layout style={{ minHeight: "100vh" }}>
<Sider width={220} theme="dark">
<div
style={{
height: 64,
display: "flex",
alignItems: "center",
justifyContent: "center",
color: "#fff",
fontSize: 18,
fontWeight: 700,
borderBottom: "1px solid rgba(255,255,255,0.1)",
}}
>
Doc Forge Reborn
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={[selectedKey]}
items={menuItems}
onClick={({ key }) => navigate(key)}
/>
</Sider>
<Layout>
<Content style={{ padding: 24, background: "#f5f5f5", overflow: "auto" }}>
<Outlet />
</Content>
</Layout>
</Layout>
);
}
+179
View File
@@ -0,0 +1,179 @@
import { useState } from "react";
import {
Modal, Button, Space, message, Card, Tag, Upload, List, Popconfirm,
} from "antd";
import {
UploadOutlined, DeleteOutlined, FileTextOutlined,
ThunderboltOutlined, PaperClipOutlined,
} from "@ant-design/icons";
import type { GenerationPoint, AIModel } from "../types";
import * as taskApi from "../api/tasks";
import request from "../api/request";
interface GenerateModalProps {
open: boolean;
onClose: () => void;
templateId: string;
points: GenerationPoint[];
models: AIModel[];
}
interface FileItem {
uid: string;
name: string;
path?: string;
}
export default function GenerateModal({
open, onClose, templateId, points, models,
}: GenerateModalProps) {
const [filesMap, setFilesMap] = useState<Record<string, FileItem[]>>({});
const [generating, setGenerating] = useState(false);
const handleUpload = async (pointId: string, fileList: File[]) => {
if (fileList.length === 0) return;
const formData = new FormData();
fileList.forEach((f) => formData.append("ref_files", f));
await request.post(`/generation-points/${pointId}/upload-ref`, formData);
const newFiles = fileList.map((f) => ({
uid: f.name + Date.now(),
name: f.name,
}));
setFilesMap((prev) => ({
...prev,
[pointId]: [...(prev[pointId] || []), ...newFiles],
}));
message.success(`已上传 ${fileList.length} 个文件`);
};
const handleRemoveFile = (pointId: string, fileName: string) => {
setFilesMap((prev) => ({
...prev,
[pointId]: (prev[pointId] || []).filter((f) => f.name !== fileName),
}));
};
const handleGenerate = async () => {
setGenerating(true);
try {
const { task_id } = await taskApi.triggerGeneration(templateId);
message.success("已创建生成任务,请前往任务历史查看");
onClose();
} catch (err: unknown) {
if (err instanceof Error) message.error(err.message);
} finally {
setGenerating(false);
}
};
const getModelName = (modelId: string | null) => {
if (!modelId) return "默认模型";
const m = models.find((x) => x.id === modelId);
return m?.name || modelId;
};
const pointsNeedRef = points.filter((p) => p.need_ref_file);
const pointsNoRef = points.filter((p) => !p.need_ref_file);
return (
<Modal
title="确认生成文档"
open={open}
onCancel={onClose}
width={700}
footer={
<Space>
<Button onClick={onClose}></Button>
<Button
type="primary"
danger
icon={<ThunderboltOutlined />}
onClick={handleGenerate}
loading={generating}
>
</Button>
</Space>
}
>
<p style={{ marginBottom: 16, color: "#666" }}>
{points.length} AI
</p>
{pointsNeedRef.length > 0 && (
<div style={{ marginBottom: 12 }}>
<Tag color="orange"> ({pointsNeedRef.length})</Tag>
</div>
)}
{points.map((point, idx) => {
const uploadedFiles = filesMap[point.id] || [];
const modelName = getModelName(point.model_id);
return (
<Card
key={point.id}
size="small"
style={{ marginBottom: 12 }}
title={
<Space size={4}>
<span style={{ fontSize: 12, color: "#999" }}>#{idx + 1}</span>
<span style={{ fontSize: 13 }}>{point.prompt.slice(0, 30)}{point.prompt.length > 30 ? "..." : ""}</span>
</Space>
}
extra={
<Tag color="blue" style={{ fontSize: 11 }}>{modelName}</Tag>
}
>
{point.remark && (
<p style={{ fontSize: 12, color: "#999", marginBottom: 8 }}>
{point.remark}
</p>
)}
{point.need_ref_file && (
<div>
<Upload
multiple
accept=".txt,.docx,.pdf"
showUploadList={false}
beforeUpload={(file) => {
handleUpload(point.id, [file]);
return false;
}}
>
<Button size="small" icon={<UploadOutlined />}>
</Button>
</Upload>
{uploadedFiles.length > 0 && (
<List
size="small"
style={{ marginTop: 8 }}
dataSource={uploadedFiles}
renderItem={(item) => (
<List.Item
extra={
<Popconfirm
title="删除此文件?"
onConfirm={() => handleRemoveFile(point.id, item.name)}
>
<Button type="text" size="small" danger icon={<DeleteOutlined />} />
</Popconfirm>
}
>
<FileTextOutlined style={{ marginRight: 6 }} />
<span style={{ fontSize: 12 }}>{item.name}</span>
</List.Item>
)}
/>
)}
</div>
)}
</Card>
);
})}
</Modal>
);
}
+15
View File
@@ -0,0 +1,15 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
#root {
width: 100%;
height: 100%;
}
+12
View File
@@ -0,0 +1,12 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>
);
+255
View File
@@ -0,0 +1,255 @@
import { useEffect, useState, useCallback } from "react";
import {
Table, Button, Modal, Form, Input, Select, Switch,
Space, message, Popconfirm, Tag,
} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined, ExperimentOutlined } from "@ant-design/icons";
import type { AIModel } from "../types";
import * as modelApi from "../api/models";
const PROVIDERS = [
{ label: "OpenAI", value: "openai" },
{ label: "Azure", value: "azure" },
{ label: "自定义", value: "custom" },
];
export default function ModelList() {
const [models, setModels] = useState<AIModel[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [editingModel, setEditingModel] = useState<AIModel | null>(null);
const [form] = Form.useForm();
const fetchModels = useCallback(async () => {
setLoading(true);
try {
const data = await modelApi.listModels();
setModels(data);
} catch {
message.error("获取模型列表失败");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchModels();
}, [fetchModels]);
const handleCreate = () => {
setEditingModel(null);
setModalOpen(true);
};
const handleEdit = (model: AIModel) => {
setEditingModel(model);
setModalOpen(true);
};
useEffect(() => {
if (!modalOpen) return;
// 延迟确保 Form DOM 已渲染
const timer = setTimeout(() => {
if (editingModel) {
const extra = editingModel.extra_params || {};
form.setFieldsValue({
name: editingModel.name,
provider: editingModel.provider,
model_name: extra.model || "",
endpoint: editingModel.endpoint,
api_key: "",
extra_params: JSON.stringify(extra, null, 2),
is_enabled: editingModel.is_enabled,
remark: editingModel.remark,
});
} else {
form.resetFields();
form.setFieldsValue({ provider: "openai", is_enabled: true, extra_params: "{}" });
}
}, 0);
return () => clearTimeout(timer);
}, [modalOpen, editingModel]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
let extraParams = {};
try {
extraParams = JSON.parse(values.extra_params || "{}");
} catch {
message.error("扩展参数 JSON 格式错误");
return;
}
const payload = {
...values,
extra_params: { ...extraParams, ...(values.model_name ? { model: values.model_name } : {}) },
};
delete payload.model_name;
if (editingModel) {
if (!payload.api_key) delete payload.api_key;
await modelApi.updateModel(editingModel.id, payload);
message.success("更新成功");
} else {
await modelApi.createModel(payload);
message.success("创建成功");
}
setModalOpen(false);
fetchModels();
} catch (err: unknown) {
if (err instanceof Error) message.error(err.message);
}
};
const handleDelete = async (id: string) => {
await modelApi.deleteModel(id);
message.success("删除成功");
fetchModels();
};
const handleToggle = async (id: string, enabled: boolean) => {
await modelApi.toggleModel(id, enabled);
fetchModels();
};
const handleTest = async (id: string, name: string) => {
message.loading({ content: `正在测试 ${name}...`, key: "test" });
try {
const res = await modelApi.testModel(id);
if (res.success) {
message.success({ content: `${name} 测试通过`, key: "test" });
Modal.info({ title: `测试结果 - ${name}`, content: res.result, width: 600 });
} else {
message.error({ content: `测试失败: ${res.error}`, key: "test", duration: 5 });
}
} catch (err: unknown) {
message.error({ content: err instanceof Error ? err.message : "测试失败", key: "test", duration: 5 });
}
};
const columns = [
{ title: "名称", dataIndex: "name", key: "name", width: 150 },
{
title: "供应商",
dataIndex: "provider",
key: "provider",
width: 80,
render: (v: string) => {
const label = PROVIDERS.find((p) => p.value === v)?.label || v;
return <Tag>{label}</Tag>;
},
},
{
title: "模型名",
key: "model_name",
width: 140,
render: (_: unknown, r: AIModel) => <Tag>{(r.extra_params as Record<string,unknown>)?.model as string || "-"}</Tag>,
},
{ title: "接口地址", dataIndex: "endpoint", key: "endpoint", ellipsis: true },
{
title: "启用",
dataIndex: "is_enabled",
key: "is_enabled",
width: 80,
render: (v: boolean, record: AIModel) => (
<Switch
checked={v}
size="small"
onChange={(checked) => handleToggle(record.id, checked)}
/>
),
},
{
title: "备注",
dataIndex: "remark",
key: "remark",
width: 150,
ellipsis: true,
render: (v: string | null) => v || "-",
},
{
title: "操作",
key: "actions",
width: 160,
render: (_: unknown, record: AIModel) => (
<Space>
<Button
type="link"
size="small"
icon={<ExperimentOutlined />}
onClick={() => handleTest(record.id, record.name)}
/>
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
/>
<Popconfirm
title="确定删除此模型?"
onConfirm={() => handleDelete(record.id)}
>
<Button type="link" size="small" danger icon={<DeleteOutlined />} />
</Popconfirm>
</Space>
),
},
];
return (
<div>
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between" }}>
<h2></h2>
<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
</Button>
</div>
<Table
columns={columns}
dataSource={models}
rowKey="id"
loading={loading}
pagination={false}
/>
<Modal
title={editingModel ? "编辑模型" : "新建模型"}
open={modalOpen}
onCancel={() => { setModalOpen(false); form.resetFields(); }}
onOk={handleSubmit}
width={600}
>
<Form form={form} layout="vertical">
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input placeholder="模型名称" />
</Form.Item>
<Form.Item name="provider" label="供应商" rules={[{ required: true }]}>
<Select options={PROVIDERS} />
</Form.Item>
<Form.Item name="model_name" label="模型名" rules={[{ required: true }]}>
<Input placeholder="例如 deepseek-chat / gpt-4 / gpt-3.5-turbo" />
</Form.Item>
<Form.Item name="endpoint" label="接口地址" rules={[{ required: true }]}>
<Input placeholder="https://api.openai.com/v1/chat/completions" />
</Form.Item>
<Form.Item
name="api_key"
label="API Key"
rules={editingModel ? [] : [{ required: true, message: "请输入 API Key" }]}
>
<Input.Password placeholder={editingModel ? "留空则不修改" : "sk-..."} />
</Form.Item>
<Form.Item name="extra_params" label="扩展参数 (JSON)">
<Input.TextArea rows={4} placeholder='{"temperature": 0.7, "max_tokens": 2000}' />
</Form.Item>
<Form.Item name="is_enabled" label="启用" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useState } from "react";
import { Card, Form, Select, InputNumber, Button, message, Spin } from "antd";
import { SaveOutlined } from "@ant-design/icons";
import * as settingsApi from "../api/settings";
import * as modelApi from "../api/models";
export default function Settings() {
const [form] = Form.useForm();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [models, setModels] = useState<{ label: string; value: string }[]>([]);
useEffect(() => {
(async () => {
try {
const [settings, modelList] = await Promise.all([
settingsApi.getAllSettings(),
modelApi.listModels({ enabled: true }),
]);
form.setFieldsValue({
default_model: settings.default_model || undefined,
max_concurrency: parseInt(settings.max_concurrency || "3", 10),
timeout: parseInt(settings.timeout || "120", 10),
});
setModels(modelList.map((m) => ({ label: m.name, value: m.id })));
} catch {
message.error("加载设置失败");
} finally {
setLoading(false);
}
})();
}, [form]);
const handleSave = async () => {
setSaving(true);
try {
const values = await form.validateFields();
await Promise.all([
settingsApi.updateSetting("default_model", values.default_model || ""),
settingsApi.updateSetting("max_concurrency", String(values.max_concurrency)),
settingsApi.updateSetting("timeout", String(values.timeout)),
]);
message.success("设置保存成功");
} catch (err: unknown) {
if (err instanceof Error) message.error(err.message);
} finally {
setSaving(false);
}
};
if (loading) return <Spin style={{ display: "block", marginTop: 100 }} />;
return (
<div style={{ maxWidth: 600 }}>
<h2 style={{ marginBottom: 16 }}></h2>
<Card>
<Form form={form} layout="vertical">
<Form.Item name="default_model" label="全局默认 AI 模型">
<Select
placeholder="留空则生成点必须指定模型"
allowClear
options={models}
notFoundContent="暂无可用模型,请先在模型管理中添加"
/>
</Form.Item>
<Form.Item name="max_concurrency" label="最大并发数" rules={[{ required: true }]}>
<InputNumber min={1} max={10} />
</Form.Item>
<Form.Item name="timeout" label="AI 调用超时(秒)" rules={[{ required: true }]}>
<InputNumber min={10} max={600} />
</Form.Item>
<Form.Item>
<Button
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
loading={saving}
>
</Button>
</Form.Item>
</Form>
</Card>
</div>
);
}
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
Card, Tag, Button, Space, Spin, Descriptions, List, Empty,
} from "antd";
import {
ArrowLeftOutlined, DownloadOutlined, FileTextOutlined,
} from "@ant-design/icons";
import request from "../api/request";
import type { GenerationPoint, AIModel } from "../types";
import * as modelApi from "../api/models";
import * as taskApi from "../api/tasks";
interface TaskDetailData {
id: string;
template_id: string;
template_name: string;
status: string;
result_file_path: string | null;
error_msg: string | null;
created_at: string;
finished_at: string | null;
points: GenerationPoint[];
}
const STATUS_MAP: Record<string, { color: string; label: string }> = {
pending: { color: "default", label: "等待中" },
processing: { color: "processing", label: "生成中" },
done: { color: "success", label: "已完成" },
failed: { color: "error", label: "失败" },
};
export default function TaskDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [task, setTask] = useState<TaskDetailData | null>(null);
const [models, setModels] = useState<AIModel[]>([]);
const [loading, setLoading] = useState(true);
const fetchTask = async () => {
if (!id) return;
setLoading(true);
try {
const { data } = await request.get<TaskDetailData>(`/tasks/${id}`, { params: { detail: true } });
setTask(data);
} catch {
setTask(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
Promise.all([
fetchTask(),
modelApi.listModels({ enabled: true }).then(setModels).catch(() => {}),
]);
}, [id]);
useEffect(() => {
if (!task || task.status === "done" || task.status === "failed") return;
const timer = setInterval(fetchTask, 3000);
return () => clearInterval(timer);
}, [task?.status]);
const getModelName = (modelId: string | null) => {
if (!modelId) return "默认模型";
return models.find((m) => m.id === modelId)?.name || modelId;
};
if (loading) return <Spin style={{ display: "block", marginTop: 100 }} />;
if (!task) return <Empty description="任务不存在" />;
const status = STATUS_MAP[task.status] || { color: "default", label: task.status };
return (
<div>
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate("/tasks")}></Button>
<h3 style={{ margin: 0 }}></h3>
</Space>
{task.status === "done" && (
<Space>
<Button icon={<DownloadOutlined />} onClick={() => window.open(taskApi.getTaskDownloadUrl(task.id))}>
DOCX
</Button>
<Button onClick={() => window.open(taskApi.getTaskDownloadUrl(task.id, "pdf"))}>
PDF
</Button>
</Space>
)}
</div>
<Card style={{ marginBottom: 16 }}>
<Descriptions column={3} size="small">
<Descriptions.Item label="模板名称">{task.template_name}</Descriptions.Item>
<Descriptions.Item label="状态"><Tag color={status.color}>{status.label}</Tag></Descriptions.Item>
<Descriptions.Item label="创建时间">{new Date(task.created_at).toLocaleString()}</Descriptions.Item>
{task.finished_at && (
<Descriptions.Item label="完成时间">{new Date(task.finished_at).toLocaleString()}</Descriptions.Item>
)}
{task.error_msg && (
<Descriptions.Item label="错误信息" span={3}>
<span style={{ color: "red" }}>{task.error_msg}</span>
</Descriptions.Item>
)}
</Descriptions>
</Card>
<h4 style={{ marginBottom: 12 }}>AI ({task.points.length})</h4>
{task.points.map((point, idx) => {
const modelName = getModelName(point.model_id);
const hasFiles = point.ref_file_path && point.ref_file_path !== "[]";
let fileNames: string[] = [];
if (hasFiles) {
try { fileNames = JSON.parse(point.ref_file_path || "[]").map((f: string) => f.split("/").pop() || f); } catch {}
}
return (
<Card
key={point.id}
size="small"
style={{ marginBottom: 8 }}
title={
<Space size={4}>
<span style={{ fontSize: 12, color: "#999" }}>#{idx + 1}</span>
<span style={{ fontSize: 13 }}>{point.prompt.slice(0, 40)}{point.prompt.length > 40 ? "..." : ""}</span>
</Space>
}
extra={<Tag color="blue">{modelName}</Tag>}
>
{point.remark && <p style={{ fontSize: 12, color: "#999", marginBottom: 8 }}>{point.remark}</p>}
{point.need_ref_file && (
<div>
{hasFiles && fileNames.length > 0 ? (
<List
size="small"
dataSource={fileNames}
renderItem={(name: string) => (
<List.Item><FileTextOutlined style={{ marginRight: 6 }} />{name}</List.Item>
)}
/>
) : (
<span style={{ fontSize: 12, color: "#999" }}></span>
)}
</div>
)}
</Card>
);
})}
</div>
);
}
+143
View File
@@ -0,0 +1,143 @@
import { useEffect, useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { Table, Button, Space, Tag, message, Popconfirm } from "antd";
import { DownloadOutlined, StopOutlined, ReloadOutlined, EyeOutlined } from "@ant-design/icons";
import type { GenerationTask } from "../types";
import * as taskApi from "../api/tasks";
const STATUS_MAP: Record<string, { color: string; label: string }> = {
pending: { color: "default", label: "等待中" },
processing: { color: "processing", label: "生成中" },
done: { color: "success", label: "已完成" },
failed: { color: "error", label: "失败" },
};
export default function TaskList() {
const navigate = useNavigate();
const [tasks, setTasks] = useState<GenerationTask[]>([]);
const [loading, setLoading] = useState(false);
const fetchTasks = useCallback(async () => {
setLoading(true);
try {
const data = await taskApi.listTasks();
setTasks(data);
} catch {
message.error("获取任务列表失败");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchTasks();
}, [fetchTasks]);
const handleCancel = async (id: string) => {
await taskApi.cancelTask(id);
message.success("已取消");
fetchTasks();
};
const columns = [
{
title: "模板 ID",
dataIndex: "template_id",
key: "template_id",
width: 120,
ellipsis: true,
render: (v: string) => v.slice(0, 8) + "...",
},
{
title: "状态",
dataIndex: "status",
key: "status",
width: 100,
render: (v: string) => {
const cfg = STATUS_MAP[v] || { color: "default", label: v };
return <Tag color={cfg.color}>{cfg.label}</Tag>;
},
},
{
title: "错误信息",
dataIndex: "error_msg",
key: "error_msg",
ellipsis: true,
render: (v: string | null) => v || "-",
},
{
title: "创建时间",
dataIndex: "created_at",
key: "created_at",
render: (v: string) => new Date(v).toLocaleString(),
},
{
title: "完成时间",
dataIndex: "finished_at",
key: "finished_at",
render: (v: string | null) => (v ? new Date(v).toLocaleString() : "-"),
},
{
title: "操作",
key: "actions",
width: 200,
render: (_: unknown, record: GenerationTask) => (
<Space>
<Button
size="small"
icon={<EyeOutlined />}
onClick={() => navigate(`/tasks/${record.id}`)}
>
</Button>
{record.status === "done" && (
<>
<Button
size="small"
icon={<DownloadOutlined />}
onClick={() => window.open(taskApi.getTaskDownloadUrl(record.id))}
>
DOCX
</Button>
<Button
size="small"
onClick={() => window.open(taskApi.getTaskDownloadUrl(record.id, "pdf"))}
>
PDF
</Button>
</>
)}
{(record.status === "pending" || record.status === "processing") && (
<Popconfirm title="确定取消此任务?" onConfirm={() => handleCancel(record.id)}>
<Button size="small" danger icon={<StopOutlined />}>
</Button>
</Popconfirm>
)}
</Space>
),
},
];
return (
<div>
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between" }}>
<h2></h2>
<Button icon={<ReloadOutlined />} onClick={fetchTasks}>
</Button>
</div>
<Table
columns={columns}
dataSource={tasks}
rowKey="id"
loading={loading}
pagination={{ pageSize: 20 }}
onRow={(record) => ({
style: { cursor: "pointer" },
onClick: () => navigate(`/tasks/${record.id}`),
})}
/>
</div>
);
}
+523
View File
@@ -0,0 +1,523 @@
import { useEffect, useState, useRef, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
Layout, Button, Modal, Form, Input, Select,
Space, message, Spin, Popconfirm, Card, Switch,
} from "antd";
import {
PlusOutlined, DeleteOutlined, EditOutlined, SaveOutlined,
ArrowLeftOutlined, ThunderboltOutlined, DownloadOutlined,
ExperimentOutlined, MenuFoldOutlined, MenuUnfoldOutlined,
MenuOutlined, PaperClipOutlined,
} from "@ant-design/icons";
import { Editor } from "@tinymce/tinymce-react";
import type { Editor as TinyMCEEditor } from "tinymce";
import type { GenerationPoint, AIModel } from "../types";
import * as templateApi from "../api/templates";
import * as pointApi from "../api/generationPoints";
import * as modelApi from "../api/models";
import request from "../api/request";
import GenerateModal from "../components/GenerateModal";
const { Sider, Content } = Layout;
export default function TemplateEditor() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const editorRef = useRef<TinyMCEEditor | null>(null);
const selectionRef = useRef<{ start: number; end: number; text: string } | null>(null);
const [htmlContent, setHtmlContent] = useState("");
const [templateName, setTemplateName] = useState("");
const [points, setPoints] = useState<GenerationPoint[]>([]);
const [models, setModels] = useState<AIModel[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [pointModalOpen, setPointModalOpen] = useState(false);
const [editingPoint, setEditingPoint] = useState<GenerationPoint | null>(null);
const [showSelectionBtn, setShowSelectionBtn] = useState(false);
const [selBtnPos, setSelBtnPos] = useState({ x: 0, y: 0 });
const [pointForm] = Form.useForm();
const [panelCollapsed, setPanelCollapsed] = useState(false);
const [generateModalOpen, setGenerateModalOpen] = useState(false);
const dragItem = useRef<number | null>(null);
const dragOverItem = useRef<number | null>(null);
const loadData = useCallback(async () => {
if (!id) return;
setLoading(true);
try {
const [template, pointsData, modelsData] = await Promise.all([
templateApi.getTemplate(id),
pointApi.listGenerationPoints(id),
modelApi.listModels({ enabled: true }),
]);
setTemplateName(template.name);
setHtmlContent(template.html_content || "");
setPoints(pointsData);
setModels(modelsData);
} catch {
message.error("加载数据失败");
} finally {
setLoading(false);
}
}, [id]);
useEffect(() => {
loadData();
}, [loadData]);
const handleSave = async () => {
if (!id) return;
setSaving(true);
try {
const html = editorRef.current?.getContent() || htmlContent;
await templateApi.updateTemplateHtml(id, html);
setHtmlContent(html);
message.success("保存成功");
} catch {
message.error("保存失败");
} finally {
setSaving(false);
}
};
const handleEditorInit = (_evt: unknown, editor: TinyMCEEditor) => {
editorRef.current = editor;
editor.on("selectionchange", () => {
const sel = editor.selection.getContent({ format: "text" });
if (sel && sel.trim().length > 0) {
const content = editor.getContent();
const rng = editor.selection.getRng();
if (rng) {
const preRange = rng.cloneRange();
preRange.selectNodeContents(editor.getBody());
preRange.setEnd(rng.startContainer, rng.startOffset);
const start = preRange.toString().length;
const end = start + sel.length;
selectionRef.current = { start, end, text: sel.trim() };
}
const ed = editor.getContainer();
const rect = ed.getBoundingClientRect();
setSelBtnPos({ x: rect.left + 100, y: rect.top + 10 });
setShowSelectionBtn(true);
} else {
setShowSelectionBtn(false);
}
});
};
const handleCreatePoint = () => {
setEditingPoint(null);
setPointModalOpen(true);
};
const handleEditPoint = (point: GenerationPoint) => {
setEditingPoint(point);
setPointModalOpen(true);
};
useEffect(() => {
if (!pointModalOpen) return;
const timer = setTimeout(() => {
if (editingPoint) {
pointForm.setFieldsValue({
prompt: editingPoint.prompt,
model_id: editingPoint.model_id,
need_ref_file: editingPoint.need_ref_file,
remark: editingPoint.remark,
});
} else {
pointForm.resetFields();
if (selectionRef.current) {
pointForm.setFieldsValue({
prompt: `根据上下文生成关于「${selectionRef.current.text.slice(0, 20)}...」的内容`,
});
}
}
}, 0);
return () => clearTimeout(timer);
}, [pointModalOpen]);
const handlePointSubmit = async () => {
if (!id) return;
try {
const values = await pointForm.validateFields();
const position = selectionRef.current
? { start: selectionRef.current.start, end: selectionRef.current.end }
: editingPoint?.position;
if (editingPoint) {
const updateData: Record<string, unknown> = {};
if (values.prompt) updateData.prompt = values.prompt;
if (values.model_id) updateData.model_id = values.model_id;
updateData.need_ref_file = values.need_ref_file || false;
if (values.remark !== undefined) updateData.remark = values.remark;
await pointApi.updateGenerationPoint(editingPoint.id, updateData);
message.success("更新成功");
} else if (position) {
await pointApi.createGenerationPoint({
template_id: id,
position: JSON.stringify(position),
prompt: values.prompt,
model_id: values.model_id,
order: points.length,
selected_text: selectionRef.current?.text,
need_ref_file: values.need_ref_file || false,
remark: values.remark || "",
});
message.success("创建成功");
selectionRef.current = null;
setShowSelectionBtn(false);
} else {
message.warning("请先在编辑器中选中文本");
return;
}
setPointModalOpen(false);
const updated = await pointApi.listGenerationPoints(id);
setPoints(updated);
} catch (err: unknown) {
if (err instanceof Error) message.error(err.message);
}
};
const handleDeletePoint = async (pointId: string) => {
try {
await pointApi.deleteGenerationPoint(pointId);
message.success("删除成功");
} catch (err: unknown) {
if (err instanceof Error) message.error(err.message);
return;
}
try {
const updated = await pointApi.listGenerationPoints(id!);
setPoints(updated);
} catch {
setPoints((prev) => prev.filter((p) => p.id !== pointId));
}
};
const handleDragStart = (_e: React.DragEvent, index: number) => {
dragItem.current = index;
};
const handleDragEnter = (_e: React.DragEvent, index: number) => {
dragOverItem.current = index;
};
const handleDragEnd = async () => {
if (dragItem.current === null || dragOverItem.current === null) return;
if (dragItem.current === dragOverItem.current) return;
const newPoints = [...points];
const [moved] = newPoints.splice(dragItem.current, 1);
newPoints.splice(dragOverItem.current!, 0, moved);
const reordered = newPoints.map((p, i) => ({ ...p, order: i }));
setPoints(reordered);
try {
await pointApi.batchUpdateOrder(
reordered.map((p) => ({ id: p.id, order: p.order }))
);
} catch {
message.error("排序更新失败");
}
dragItem.current = null;
dragOverItem.current = null;
};
const handleTestPoint = async (pointId: string) => {
const point = points.find((p) => p.id === pointId);
if (!point) return;
if (point.need_ref_file) {
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.multiple = true;
fileInput.accept = ".txt,.docx,.pdf";
fileInput.onchange = async (e: Event) => {
const files = (e.target as HTMLInputElement).files;
if (!files || files.length === 0) return;
try {
message.loading({ content: "测试中...", key: "test" });
const formData = new FormData();
Array.from(files).forEach((f) => formData.append("ref_files", f));
const { default: request } = await import("../api/request");
const { data } = await request.post<{ result: string }>(
`/generation-points/${pointId}/test`,
formData
);
message.success({ content: "测试完成", key: "test" });
Modal.info({ title: "AI 生成结果", content: data.result, width: 600 });
} catch {
message.error({ content: "测试失败", key: "test" });
}
};
fileInput.click();
return;
}
try {
message.loading({ content: "测试中...", key: "test" });
const result = await pointApi.testGenerationPoint(pointId);
message.success({ content: "测试完成", key: "test" });
Modal.info({ title: "AI 生成结果", content: result, width: 600 });
} catch {
message.error({ content: "测试失败", key: "test" });
}
};
const handleGenerate = () => {
if (!id) return;
if (points.length === 0) {
message.warning("请先添加至少一个生成点");
return;
}
setGenerateModalOpen(true);
};
if (loading) {
return (
<div style={{ textAlign: "center", padding: 100 }}>
<Spin size="large" />
</div>
);
}
return (
<div style={{ height: "calc(100vh - 120px)" }}>
<div
style={{
marginBottom: 12,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate("/templates")}>
</Button>
<h3 style={{ margin: 0 }}>{templateName}</h3>
</Space>
<Space>
<Button
icon={panelCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={() => setPanelCollapsed(!panelCollapsed)}
/>
<Button icon={<SaveOutlined />} onClick={handleSave} loading={saving}>
</Button>
<Button
type="primary"
danger
icon={<ThunderboltOutlined />}
onClick={handleGenerate}
>
</Button>
</Space>
</div>
<Layout style={{ height: "calc(100% - 50px)", background: "#fff" }}>
<Content style={{ position: "relative", overflow: "hidden" }}>
{showSelectionBtn && (
<div style={{
position: "absolute",
zIndex: 1310,
top: 0,
right: 8,
padding: "4px 8px",
background: "#fff",
borderRadius: "0 0 4px 4px",
boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
}}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={handleCreatePoint}
>
AI
</Button>
</div>
)}
<Editor
key={id}
tinymceScriptSrc="/tinymce/tinymce.min.js"
initialValue={htmlContent}
onInit={handleEditorInit}
init={{
height: "100%",
menubar: true,
license_key: "gpl",
plugins: [
"advlist", "autolink", "lists", "link", "image",
"charmap", "preview", "anchor", "searchreplace",
"visualblocks", "code", "fullscreen", "insertdatetime",
"media", "table", "help", "wordcount",
],
toolbar:
"undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help",
content_style: "body { font-family: Arial, sans-serif; font-size: 14px; }",
valid_elements: "*[*]",
extended_valid_elements: "p[style],h1[style],h2[style],h3[style],h4[style],h5[style],h6[style],div[style],span[style],li[style]",
}}
/>
</Content>
{!panelCollapsed && (
<Sider width={320} theme="light" style={{ padding: 16, overflow: "auto", borderLeft: "1px solid #f0f0f0" }}>
<h4 style={{ marginBottom: 12 }}> ({points.length})</h4>
{points.map((point, index) => {
const model = models.find((m) => m.id === point.model_id);
return (
<div
key={point.id}
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDragEnter={(e) => handleDragEnter(e, index)}
onDragEnd={handleDragEnd}
onDragOver={(e) => e.preventDefault()}
style={{ marginBottom: 8, cursor: "grab" }}
>
<Card
size="small"
title={
<Space size={4}>
<MenuOutlined style={{ color: "#bbb", fontSize: 12, cursor: "grab" }} />
<span style={{ fontSize: 12, color: "#999" }}>#{index + 1}</span>
{model && (
<span style={{ fontSize: 12, color: "#1677ff" }}>
{model.name}
</span>
)}
</Space>
}
extra={
<Space size={4}>
{point.need_ref_file && (
<Button
type="text"
size="small"
icon={<PaperClipOutlined />}
onClick={async () => {
const input = document.createElement("input");
input.type = "file";
input.multiple = true;
input.accept = ".txt,.docx,.pdf";
input.onchange = async (e) => {
const files = (e.target as HTMLInputElement).files;
if (!files?.length) return;
const fd = new FormData();
Array.from(files).forEach((f) => fd.append("ref_files", f));
await request.post(`/generation-points/${point.id}/upload-ref`, fd);
message.success("上传成功");
const updated = await pointApi.listGenerationPoints(id!);
setPoints(updated);
};
input.click();
}}
/>
)}
<Button
type="text"
size="small"
icon={<ExperimentOutlined />}
onClick={() => handleTestPoint(point.id)}
/>
<Button
type="text"
size="small"
icon={<EditOutlined />}
onClick={() => handleEditPoint(point)}
/>
<Popconfirm
title="确定删除?"
onConfirm={() => handleDeletePoint(point.id)}
>
<Button type="text" size="small" danger icon={<DeleteOutlined />} />
</Popconfirm>
</Space>
}
>
<p style={{ fontSize: 12, color: "#666", margin: 0, wordBreak: "break-all" }}>
{point.prompt.slice(0, 80)}
{point.prompt.length > 80 && "..."}
</p>
</Card>
</div>
);
})}
{points.length === 0 && (
<p style={{ color: "#999", fontSize: 13 }}>
"设为 AI 生成点"
</p>
)}
</Sider>
)}
</Layout>
<Modal
title={editingPoint ? "编辑生成点" : "新建生成点"}
open={pointModalOpen}
onCancel={() => { setPointModalOpen(false); pointForm.resetFields(); }}
onOk={handlePointSubmit}
width={560}
>
<Form form={pointForm} layout="vertical">
{selectionRef.current && !editingPoint && (
<div
style={{
marginBottom: 12,
padding: 8,
background: "#f6f8fa",
borderRadius: 6,
fontSize: 13,
color: "#666",
}}
>
: {selectionRef.current.text.slice(0, 50)}
{selectionRef.current.text.length > 50 ? "..." : ""}
</div>
)}
<Form.Item name="prompt" label="提示词" rules={[{ required: true }]}>
<Input.TextArea
rows={4}
placeholder="请输入 AI 生成提示词,例如:请根据参考文件内容,生成一段项目背景介绍..."
/>
</Form.Item>
<Form.Item name="model_id" label="AI 模型">
<Select
allowClear
placeholder="留空则使用全局默认模型"
options={models.map((m) => ({ label: m.name, value: m.id }))}
/>
</Form.Item>
<Form.Item name="need_ref_file" label="需要参考文件" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} placeholder="补充说明(可选)" />
</Form.Item>
</Form>
</Modal>
<GenerateModal
open={generateModalOpen}
onClose={async () => {
setGenerateModalOpen(false);
try {
const updated = await pointApi.listGenerationPoints(id!);
setPoints(updated);
} catch {}
}}
templateId={id || ""}
points={points}
models={models}
/>
</div>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useState, useCallback } from "react";
import { Table, Button, Upload, Space, message, Popconfirm } from "antd";
import { EditOutlined, DeleteOutlined, DownloadOutlined, PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import type { TemplateListItem } from "../types";
import * as templateApi from "../api/templates";
export default function TemplateList() {
const navigate = useNavigate();
const [templates, setTemplates] = useState<TemplateListItem[]>([]);
const [loading, setLoading] = useState(false);
const [refresh, setRefresh] = useState(0);
const fetchTemplates = useCallback(async () => {
setLoading(true);
try {
const data = await templateApi.listTemplates();
setTemplates(data);
} catch {
message.error("获取模板列表失败");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchTemplates();
}, [fetchTemplates, refresh]);
const handleDelete = async (id: string) => {
await templateApi.deleteTemplate(id);
message.success("删除成功");
setRefresh((r) => r + 1);
};
const columns = [
{ title: "模板名称", dataIndex: "name", key: "name" },
{
title: "创建时间",
dataIndex: "created_at",
key: "created_at",
render: (v: string) => new Date(v).toLocaleString(),
},
{
title: "更新时间",
dataIndex: "updated_at",
key: "updated_at",
render: (v: string) => new Date(v).toLocaleString(),
},
{
title: "操作",
key: "actions",
width: 240,
render: (_: unknown, record: TemplateListItem) => (
<Space>
<Button
type="primary"
size="small"
icon={<EditOutlined />}
onClick={() => navigate(`/editor/${record.id}`)}
>
</Button>
<Button
size="small"
icon={<DownloadOutlined />}
onClick={() => window.open(templateApi.getDownloadUrl(record.id))}
>
DOCX
</Button>
<Button
size="small"
onClick={() => window.open(templateApi.getDownloadUrl(record.id, "pdf"))}
>
PDF
</Button>
<Popconfirm title="确定删除此模板?" onConfirm={() => handleDelete(record.id)}>
<Button size="small" danger icon={<DeleteOutlined />} />
</Popconfirm>
</Space>
),
},
];
return (
<div>
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between" }}>
<h2></h2>
<Upload
accept=".docx"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
try {
await templateApi.uploadTemplate(file as File);
message.success("上传成功");
setRefresh((r) => r + 1);
onSuccess?.("ok");
} catch {
message.error("上传失败");
onError?.(new Error("上传失败"));
}
}}
>
<Button type="primary" icon={<PlusOutlined />}>
</Button>
</Upload>
</div>
<Table
columns={columns}
dataSource={templates}
rowKey="id"
loading={loading}
pagination={false}
/>
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
export interface AIModel {
id: string;
name: string;
provider: string;
endpoint: string;
api_key: string;
extra_params: Record<string, unknown>;
is_enabled: boolean;
remark: string | null;
created_at: string;
updated_at: string;
}
export interface Template {
id: string;
name: string;
file_path: string;
html_content: string | null;
created_at: string;
updated_at: string;
}
export interface TemplateListItem {
id: string;
name: string;
created_at: string;
updated_at: string;
}
export interface GenerationPoint {
id: string;
template_id: string;
position: { start: number; end: number };
prompt: string;
model_id: string | null;
ref_file_path: string | null;
need_ref_file: boolean;
remark: string | null;
order: number;
selected_text: string | null;
created_at: string;
updated_at: string;
}
export interface GenerationTask {
id: string;
template_id: string;
template_name?: string;
status: "pending" | "processing" | "done" | "failed";
result_file_path: string | null;
error_msg: string | null;
created_at: string;
finished_at: string | null;
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
proxy: {
"/api": {
target: "http://localhost:8000",
changeOrigin: true,
},
},
},
});