Merge branch 'test' into prod

# Conflicts:
#	backend/.env
This commit is contained in:
sophie committed 2026-05-16 14:56:51 +08:00
commit 729ec2908d
105 files changed
+21090 -1150

No files matched your search

+5 -3
View File
@@ -1,4 +1,6 @@
FROM node:22-alpine AS builder
ARG NODE_BASE_IMAGE=node:22-alpine
ARG NGINX_BASE_IMAGE=nginx:alpine
FROM ${NODE_BASE_IMAGE} AS builder
WORKDIR /app
COPY package*.json ./
@@ -6,10 +8,10 @@ RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
FROM ${NGINX_BASE_IMAGE}
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
CMD ["nginx", "-g", "daemon off;"]
+2 -2
View File
@@ -10,8 +10,8 @@
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-cKdfgj1g.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DY8VTReJ.css">
<script type="module" crossorigin src="/assets/index-grYi-CaK.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DvLiupE9.css">
</head>
<body>
<div id="app"></div>␍
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

+8 -3
View File
@@ -1,6 +1,9 @@
server {
listen 80;
server_name localhost;
client_max_body_size 100m;
resolver 127.0.0.11 valid=30s ipv6=off;
resolver_timeout 5s;
# 静态资源服务
location / {
@@ -11,9 +14,11 @@ server {
# API 代理到后端
location /api/ {
# 注意: 这里使用 Docker Compose 服务名
# 使用 /api/ 后缀确保传递完整路径
proxy_pass http://hxops-backend:5000/api/;
# 通过 Docker 内置 DNS 动态解析后端服务,避免后端容器重建后
# Nginx 继续使用启动时缓存的旧 IP 而出现 502。
set $backend_upstream hxops-backend:5000;
# 变量形式下不要附带 URI,保留原始 /api/... 路径透传给后端。
proxy_pass http://$backend_upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-8
View File
@@ -542,7 +542,6 @@
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -949,7 +948,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -2040,7 +2038,6 @@
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -2085,7 +2082,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -2444,7 +2440,6 @@
"resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -2546,7 +2541,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -2605,7 +2599,6 @@
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@oxc-project/runtime": "0.114.0",
"lightningcss": "^1.31.1",
@@ -2691,7 +2684,6 @@
"resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz",
"integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.28",
"@vue/compiler-sfc": "3.5.28",
+8 -44
View File
@@ -1,53 +1,17 @@
const CACHE_NAME = 'hxops-shell-v2';
const OFFLINE_ASSETS = ['/', '/workspace', '/manifest.webmanifest', '/vite.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(OFFLINE_ASSETS)).catch(() => null)
self.skipWaiting()
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
)
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const request = event.request;
if (request.method !== 'GET') return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith('/api/')) return;
if (url.pathname.startsWith('/@vite/')) return;
if (url.pathname.includes('/__vite_ping')) return;
if (request.mode === 'navigate') {
event.respondWith(
fetch(request).catch(() => caches.match('/workspace').then((res) => res || caches.match('/')))
);
return;
}
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)).catch(() => null);
return response;
})
.catch(() => caches.match('/vite.svg'));
})
(async () => {
const keys = await caches.keys();
await Promise.all(keys.map((key) => caches.delete(key)));
await self.clients.claim();
const registrations = await self.registration.unregister();
return registrations;
})()
);
});
+557
View File
@@ -0,0 +1,557 @@
import { getAuthHeaders } from '../utils/auth';
export interface KbGroup {
id: number;
name: string;
description?: string | null;
department_id?: number | null;
document_count?: number;
created_at?: string | null;
updated_at?: string | null;
}
export interface KbDocumentItem {
id: number;
group_id?: number;
title: string;
description?: string | null;
status?: string;
source_type?: string | null;
created_at?: string | null;
updated_at?: string;
version_count?: number;
latest_version?: KbDocumentVersionItem | null;
}
export interface KbDocumentVersionItem {
id: number;
document_id: number;
version_no: number;
status: string;
is_current: boolean;
source_file_name: string;
source_file_ext?: string | null;
source_file_size?: number | null;
sha256?: string | null;
cleaned_file_path?: string | null;
cleaned_preview_path?: string | null;
error_message?: string | null;
created_at?: string | null;
}
export interface KbSyncRecordItem {
id: number;
group_id?: number | null;
document_id?: number | null;
document_version_id: number;
dataset_id: string;
dataset_name?: string | null;
remote_document_id: string;
remote_document_name?: string | null;
status: string;
sync_hash?: string | null;
error_message?: string | null;
synced_at?: string | null;
updated_at?: string | null;
}
export interface KbDocumentMarkdown {
document_id: number;
title: string;
version: KbDocumentVersionItem | null;
content: string;
kind: 'markdown' | 'preview';
}
export interface KbJob {
id: number | string;
job_type: string;
status: string;
group_id?: number | null;
document_id?: number | null;
document_version_id?: number | null;
progress?: number;
message?: string | null;
error_message?: string | null;
payload_json?: Record<string, any> | null;
result_json?: Record<string, any> | null;
created_at?: string;
started_at?: string | null;
finished_at?: string | null;
}
export interface KbDifySettings {
DIFY_API_BASE: string;
DIFY_API_KEY: string;
KB_DIFY_PERMISSION: string;
KB_DIFY_INDEXING_TECHNIQUE: string;
KB_DIFY_SEARCH_METHOD: string;
KB_DIFY_DOC_FORM: string;
dify_api_configured?: boolean;
}
export interface KbDifyHealth {
dify_base_url: string;
dify_api_configured: boolean;
api: {
configured: boolean;
reachable: boolean;
dataset_count?: number | null;
error?: string | null;
};
local_sync_health: {
dataset_bound_groups: number;
sync_records: number;
syncing_versions: number;
synced_versions: number;
failed_sync_records: number;
pending_sync_jobs: number;
};
}
export interface KbListResponse<T> {
ok: boolean;
data: T;
error?: string;
status?: number;
}
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
try {
const res = await fetch(path, { headers: getAuthHeaders() });
if (!res.ok) return fallback;
return (await res.json()) as T;
} catch {
return fallback;
}
};
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
try {
const res = await fetch(path, { headers: getAuthHeaders() });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return {
ok: false,
data: fallback,
error: data?.error || '知识库接口请求失败',
status: res.status,
};
}
return { ok: true, data: (await res.json()) as T, status: res.status };
} catch {
return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbGroups = async (): Promise<KbGroup[]> => {
return getJson<KbGroup[]>('/api/kb/groups', []);
};
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
};
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
};
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
};
export const createKbGroup = async (payload: {
name: string;
description?: string;
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch('/api/kb/groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '创建知识库分组失败' };
}
return { ok: true, group: (await res.json()) as KbGroup };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbJobs = async (): Promise<KbJob[]> => {
return getJson<KbJob[]>('/api/kb/jobs', []);
};
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
};
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
};
export const updateKbDifySettings = async (
payload: Partial<KbDifySettings>
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
try {
const res = await fetch('/api/kb/dify/settings', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '保存 Dify 设置失败' };
}
return { ok: true, settings: (await res.json()) as KbDifySettings };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
};
export const runKbJob = async (
jobId: number | string
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
try {
const res = await fetch(`/api/kb/jobs/${jobId}/run`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '执行任务失败' };
}
const job = (await res.json()) as KbJob & { run_result?: string };
return { ok: true, job, run_result: job.run_result };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const createKbDocument = async (
groupId: number,
payload: { title: string; description?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '创建文档失败' };
}
return { ok: true, document: (await res.json()) as KbDocumentItem };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbDocument = async (
documentId: number,
payload: { title: string; description?: string; status?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '更新文档失败' };
}
return { ok: true, document: (await res.json()) as KbDocumentItem };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const deleteKbDocument = async (
documentId: number
): Promise<{ ok: boolean; error?: string }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '删除文档失败' };
}
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDocumentVersions = async (
documentId: number
): Promise<KbDocumentVersionItem[]> => {
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
};
export const getKbDocumentVersionSourceFile = async (
versionId: number
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
try {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '读取原始文件失败' };
}
const disposition = res.headers.get('content-disposition') || '';
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
return {
ok: true,
blob: await res.blob(),
filename: filename || undefined,
contentType: res.headers.get('content-type') || undefined,
};
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDocumentSyncRecords = async (
documentId: number
): Promise<KbSyncRecordItem[]> => {
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
};
export const getKbDocumentMarkdown = async (
documentId: number
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' };
}
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbDocumentMarkdown = async (
documentId: number,
payload: { content: string }
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '保存 Markdown 失败' };
}
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const uploadKbDocumentVersion = async (
documentId: number,
file: File
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => {
try {
const formData = new FormData();
formData.append('file', file);
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
if (!res.ok) {
if (res.status === 413) {
return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status };
}
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '上传文档版本失败', status: res.status };
}
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const createKbPathUploadJob = async (
groupId: number,
payload: { total_files: number; selected_paths: string[] }
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status };
}
return { ok: true, job: data as KbJob, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const uploadKbPathJobFile = async (
jobId: number | string,
file: File,
relativePath: string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const formData = new FormData();
formData.append('file', file);
formData.append('relative_path', relativePath);
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '上传路径文件失败' };
}
return { ok: true, job: data as KbJob };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const finalizeKbPathUploadJob = async (
jobId: number | string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
method: 'POST',
headers: getAuthHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '提交路径上传任务失败' };
}
return { ok: true, job: data as KbJob };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const retryFailedKbPathUploadJob = async (
jobId: number | string,
payload?: { relative_paths?: string[] },
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload || {}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '重试失败文件失败', status: res.status };
}
return { ok: true, job: data as KbJob, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const syncKbDocumentToDify = async (
documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/sync`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' };
}
const job = (await res.json()) as KbJob & { run_result?: string };
return { ok: true, job, run_result: job.run_result };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbGroup = async (
groupId: number,
payload: { name: string; description?: string }
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '更新知识库分组失败' };
}
return { ok: true, group: (await res.json()) as KbGroup };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const deleteKbGroup = async (
groupId: number
): Promise<{ ok: boolean; error?: string }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '删除知识库分组失败' };
}
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { getKbDifyHealth, type KbDifyHealth } from '../../api/kb';
const props = defineProps<{
open: boolean;
}>();
const emit = defineEmits<{
close: [];
error: [message: string];
}>();
const loading = ref(false);
const payload = ref<KbDifyHealth | null>(null);
const close = () => emit('close');
const loadHealth = async () => {
loading.value = true;
payload.value = await getKbDifyHealth();
loading.value = false;
if (!payload.value) {
emit('error', '加载 Dify 健康状态失败');
}
};
watch(
() => props.open,
(open) => {
if (open) {
void loadHealth();
}
}
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="w-full max-w-4xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 健康检查</h3>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
查看知识库模块当前的 Dify 连接情况和本地同步概况。
</p>
</div>
<div class="flex items-center gap-3">
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="loadHealth">
刷新
</button>
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
关闭
</button>
</div>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在检测...</div>
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dify API</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.api.reachable ? '可访问' : '不可访问' }}
</div>
<div class="mt-2 break-all text-xs text-slate-500 dark:text-slate-400">
{{ payload.dify_base_url || '未配置' }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dataset 数量</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.api.dataset_count ?? '--' }}
</div>
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
配置完成:{{ payload.dify_api_configured ? '是' : '否' }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已绑定分组</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.dataset_bound_groups }}
</div>
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
本地同步记录:{{ payload.local_sync_health.sync_records }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">同步中版本</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.syncing_versions }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已同步版本</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.synced_versions }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">待同步任务</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.pending_sync_jobs }}
</div>
<div class="mt-2 text-xs text-rose-500" v-if="payload.api.error">
{{ payload.api.error }}
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,134 @@
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { getKbDifySettings, updateKbDifySettings } from '../../api/kb';
const props = defineProps<{
open: boolean;
}>();
const emit = defineEmits<{
close: [];
saved: [message: string];
error: [message: string];
}>();
const loading = ref(false);
const saving = ref(false);
const form = reactive({
DIFY_API_BASE: '',
DIFY_API_KEY: '',
KB_DIFY_PERMISSION: 'only_me',
KB_DIFY_INDEXING_TECHNIQUE: 'high_quality',
KB_DIFY_SEARCH_METHOD: 'semantic_search',
KB_DIFY_DOC_FORM: 'text_model',
});
const close = () => emit('close');
const loadSettings = async () => {
loading.value = true;
const settings = await getKbDifySettings();
loading.value = false;
if (!settings) {
emit('error', '加载 Dify 设置失败');
return;
}
Object.assign(form, settings);
};
const save = async () => {
saving.value = true;
const result = await updateKbDifySettings(form);
saving.value = false;
if (!result.ok) {
emit('error', result.error || '保存 Dify 设置失败');
return;
}
emit('saved', 'Dify 设置已保存');
emit('close');
};
watch(
() => props.open,
(open) => {
if (open) {
void loadSettings();
}
}
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="w-full max-w-3xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 设置</h3>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
管理知识库模块使用的 Dify 连接和默认同步参数。
</p>
</div>
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
关闭
</button>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在加载设置...</div>
<div v-else class="mt-6 grid gap-4 md:grid-cols-2">
<label class="space-y-2 md:col-span-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify Base URL</span>
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
</label>
<label class="space-y-2 md:col-span-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify API Key</span>
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Permission</span>
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
<option value="only_me">only_me</option>
<option value="all_team_members">all_team_members</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Indexing Technique</span>
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
<option value="high_quality">high_quality</option>
<option value="economy">economy</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Search Method</span>
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
<option value="semantic_search">semantic_search</option>
<option value="hybrid_search">hybrid_search</option>
<option value="full_text_search">full_text_search</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Doc Form</span>
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
<option value="text_model">text_model</option>
</select>
</label>
</div>
<div class="mt-6 flex justify-end gap-3">
<button class="rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800" @click="close">
取消
</button>
<button
class="rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="saving"
@click="save"
>
{{ saving ? '保存中...' : '保存设置' }}
</button>
</div>
</div>
</div>
</template>
+13 -6
View File
@@ -1,4 +1,4 @@
import { createApp } from 'vue'
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
@@ -52,10 +52,17 @@ createApp(App)
.use(i18n)
.mount('#app')
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').catch((err) => {
console.error('Service worker registration failed:', err);
});
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
try {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => registration.unregister()));
if ('caches' in window) {
const cacheKeys = await window.caches.keys();
await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
}
} catch (err) {
console.error('Service worker cleanup failed:', err);
}
});
}
+14
View File
@@ -6,6 +6,8 @@ import ChatView from '../views/ChatView.vue';
import AdminView from '../views/AdminView.vue';
import ProfileView from '../views/ProfileView.vue';
import ResetPasswordView from '../views/ResetPasswordView.vue';
import KbWorkspaceView from '../views/KbWorkspaceView.vue';
import KbAdminView from '../views/KbAdminView.vue';
import { config } from '../config';
import { getStoredAuthUser } from '../utils/auth';
@@ -45,6 +47,18 @@ const routes = [
name: 'Admin',
component: AdminView
},
{
path: '/kb/workspace',
name: 'KbWorkspace',
component: KbWorkspaceView,
meta: { title: '知识库工作台' }
},
{
path: '/kb/admin',
name: 'KbAdmin',
component: KbAdminView,
meta: { title: '知识库管理台' }
},
];
+7
View File
@@ -2544,6 +2544,13 @@ const handlePermissionImport = async (event: Event) => {
</div>
</div>
<div class="flex items-center gap-4">
<button
@click="router.push('/kb/admin')"
class="hidden md:inline-flex items-center gap-2 rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
>
<Settings2 class="w-4 h-4" />
<span>知识库管理</span>
</button>
<ThemeToggleButton />
<!-- Language Selector -->
<div class="flex items-center gap-2">
+559 -152
View File
@@ -10,10 +10,10 @@
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
*/
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink } from 'lucide-vue-next';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search } from 'lucide-vue-next';
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
@@ -32,6 +32,8 @@ const selectedKb = ref('企业知识库');
const showKbDropdown = ref(false);
const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null;
marked.setOptions({
gfm: true,
@@ -41,8 +43,10 @@ marked.setOptions({
const currentUserDisplayName = computed(() => {
const realName = currentUser.value?.real_name?.trim();
if (realName) return realName;
const aliasName = (currentUser.value as any)?.name?.trim?.() || (currentUser.value as any)?.wecom_name?.trim?.();
if (aliasName) return aliasName;
const username = currentUser.value?.username?.trim();
if (username) return username;
if (username && !/^\d+$/.test(username)) return username;
return '当前用户';
});
@@ -429,61 +433,47 @@ const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
const showGeneralFeedbackDialog = ref(false);
const showOALoginModal = ref(false);
const oaLoginForm = ref({ username: '', password: '' });
const openOALoginModal = () => {
oaLoginForm.value = {
username: currentUserEmployeeId.value || currentUser.value?.username || '',
password: ''
};
showOALoginModal.value = true;
};
const OA_LOGIN_URL = 'http://192.168.100.221:8888/login/Login.jsp?logintype=1';
const OA_VERIFY_LOGIN_URL = 'http://192.168.100.221:8888/login/VerifyLogin.jsp';
const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
const OA_AUTO_LOGIN_USERNAME = '26040006';
const OA_AUTO_LOGIN_PASSWORD = '26040006';
const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
const submitOALogin = () => {
if (!oaLoginForm.value.username || !oaLoginForm.value.password) {
showMessageDialog('error', '请输入账号和密码');
const openOALeaveRequestDirectly = () => {
const popup = window.open(OA_LOGIN_URL, OA_AUTO_LOGIN_TARGET);
if (!popup) {
showMessageDialog('warning', '浏览器拦截了 OA 页面,请允许弹出窗口后重试。');
return;
}
// 要跳转的目标 OA 页面
const targetUrl = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
// 创建隐藏表单进行 POST 提交到 OA 登录接口
const form = document.createElement('form');
form.action = 'http://192.168.100.221:8888/login/VerifyLogin.jsp';
form.action = OA_VERIFY_LOGIN_URL;
form.method = 'POST';
form.target = '_blank';
const inputLoginId = document.createElement('input');
inputLoginId.type = 'hidden';
inputLoginId.name = 'loginid';
inputLoginId.value = oaLoginForm.value.username;
form.appendChild(inputLoginId);
const inputPassword = document.createElement('input');
inputPassword.type = 'hidden';
inputPassword.name = 'userpassword';
inputPassword.value = oaLoginForm.value.password;
form.appendChild(inputPassword);
const inputGoPage = document.createElement('input');
inputGoPage.type = 'hidden';
inputGoPage.name = 'gopage';
inputGoPage.value = targetUrl;
form.appendChild(inputGoPage);
const inputLogintype = document.createElement('input');
inputLogintype.type = 'hidden';
inputLogintype.name = 'logintype';
inputLogintype.value = '1';
form.appendChild(inputLogintype);
form.target = OA_AUTO_LOGIN_TARGET;
form.style.display = 'none';
const fields = {
loginid: OA_AUTO_LOGIN_USERNAME,
userpassword: OA_AUTO_LOGIN_PASSWORD,
gopage: OA_LEAVE_APPLY_PATH,
logintype: '1',
};
Object.entries(fields).forEach(([name, value]) => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
showOALoginModal.value = false;
window.setTimeout(() => {
form.submit();
document.body.removeChild(form);
}, 0);
};
const activeFeedbackMessageIndex = ref<number | null>(null);
@@ -531,13 +521,18 @@ const LEAVE_RESULT_QUERY_URL = 'http://192.168.100.221:8888/';
interface LeaveRequestFormData {
applicantName: string;
employeeId: string;
applicantUid: string;
applyTime: string;
fillerName: string;
agentUid: string;
agentEmployeeId: string;
agentName: string;
leaveType: string;
startTime: string;
endTime: string;
durationHours: number;
isOutOfOffice: boolean;
isWorkInjury: boolean;
isOutOfOffice: 0 | 1 | null;
isWorkInjury: 0 | 1 | null;
}
interface LeaveFormPayload {
@@ -559,9 +554,83 @@ interface LeaveResultPayload {
success: boolean;
referenceNo: string;
submittedAt: string;
requestName?: string;
errorMessage?: string;
}
interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
}
let leaveFlowCounter = 0;
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
const leaveAgentLoading = ref(false);
const leaveAgentKeyword = ref('');
const leaveAgentPage = ref(1);
const leaveAgentHasMore = ref(true);
const fetchLeaveAgents = async (isLoadMore = false) => {
if (leaveAgentLoading.value) return;
if (!isLoadMore) {
leaveAgentPage.value = 1;
leaveAgentOptions.value = [];
}
leaveAgentLoading.value = true;
try {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=${leaveAgentPage.value}&page_size=20&agent_id=${agentId}`, {
headers: getAuthHeaders()
});
if (res.ok) {
const data = await res.json();
if (isLoadMore) {
leaveAgentOptions.value.push(...data.items);
} else {
leaveAgentOptions.value = data.items;
}
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
}
} catch (e) {
console.error('Failed to load OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const handleAgentSearch = () => {
fetchLeaveAgents(false);
};
const loadMoreAgents = () => {
if (!leaveAgentHasMore.value) return;
leaveAgentPage.value += 1;
fetchLeaveAgents(true);
};
const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=1&page_size=100000&agent_id=${agentId}`, {
headers: getAuthHeaders()
});
if (res.ok) {
const data = await res.json();
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
}
} catch (e) {
console.error('Failed to load all OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const showLeaveAgentDialog = ref(false);
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
const activeLeaveAgentFormId = ref<string | null>(null);
const formatDateTime = (date: Date) => {
const year = date.getFullYear();
@@ -605,13 +674,18 @@ const createLeaveFormData = (): LeaveRequestFormData => {
return {
applicantName: currentUserDisplayName.value,
employeeId: currentUserEmployeeId.value,
applicantUid: '',
applyTime: formatDateTime(now),
fillerName: currentUserDisplayName.value,
agentUid: '',
agentEmployeeId: '',
agentName: '',
leaveType: '',
startTime,
endTime,
durationHours: calculateDurationHours(startTime, endTime),
isOutOfOffice: false,
isWorkInjury: false,
isOutOfOffice: 1,
isWorkInjury: 1,
};
};
@@ -628,10 +702,45 @@ const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\
const isStrongLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content);
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程)/.test(normalized);
// 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/;
if (weakConsultationIntent.test(normalized)) return false;
if (/^(请假|休假)$/.test(normalized)) return true;
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized);
};
const startLocalLeaveFlow = (content: string) => {
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
try {
const res = await fetch('/api/chat/messages/local', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
conversation_id: conversationId.value,
type: msg.type,
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: agentId
})
});
if (res.ok) {
const data = await res.json();
if (!conversationId.value && data.conversation_id) {
conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
msg.chat_log_id = data.chat_log_id;
}
}
} catch (e) {
console.error('Failed to save local message', e);
}
};
const startLocalLeaveFlow = async (content: string) => {
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
@@ -639,15 +748,34 @@ const startLocalLeaveFlow = (content: string) => {
submitting: false,
confirmationGenerated: false,
};
messages.value.push({ role: 'user', content, type: 'text' });
messages.value.push({
role: 'assistant',
type: 'leave-form',
const formMsg = {
role: 'assistant' as const,
type: 'leave-form' as const,
content: '已为你生成请假申请表,请直接在下方填写并提交。或登录OA系统直接申请',
payload,
local_id: formId,
local_only: true,
});
};
messages.value.push(formMsg);
await saveLocalMessageToBackend(formMsg, content);
// 发送完成后刷新历史记录,确保新会话出现
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
await loadHistory();
}
};
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
if (!actionElement) return;
const action = actionElement.getAttribute('data-leave-action');
if (action !== 'start-leave-flow' || isThinking.value) return;
event.preventDefault();
startLocalLeaveFlow('我要请假');
};
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (
@@ -662,13 +790,101 @@ const getLeaveResultPayload = (msg: any): LeaveResultPayload | null => (
msg?.type === 'leave-result' && msg?.payload ? msg.payload as LeaveResultPayload : null
);
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId);
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId || msg?.payload?.formId === localId);
const getLeaveAgentDisplayValue = (form: LeaveRequestFormData) => {
if (!form.agentName) return '';
const parts = [form.agentName];
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
return parts.join(' / ');
};
const formatYesNoLabel = (value: 0 | 1 | null) => {
if (value === 0) return '是';
if (value === 1) return '否';
return '未选择';
};
const syncCurrentUserProfile = async () => {
if (currentUser.value?.real_name?.trim()) return;
try {
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
if (!res.ok) return;
const data = await res.json();
currentUser.value = { ...currentUser.value, ...data };
} catch (e) {
console.error('Failed to load current user profile', e);
}
};
const openLeaveAgentDialog = (msg: any, role: 'agent' | 'applicant' = 'agent') => {
const payload = getLeaveFormPayload(msg);
if (!payload || payload.submitting || payload.confirmationGenerated) return;
activeLeaveAgentFormId.value = payload.formId;
leaveUserSelectRole.value = role;
showLeaveAgentDialog.value = true;
leaveAgentKeyword.value = '';
fetchLeaveAgents(false);
};
const closeLeaveAgentDialog = () => {
showLeaveAgentDialog.value = false;
activeLeaveAgentFormId.value = null;
};
const selectLeaveAgent = (option: LeaveAgentOption) => {
if (!activeLeaveAgentFormId.value) return;
const sourceIndex = findMessageIndexByLocalId(activeLeaveAgentFormId.value);
if (sourceIndex < 0) {
closeLeaveAgentDialog();
return;
}
const payload = getLeaveFormPayload(messages.value[sourceIndex]);
if (!payload) {
closeLeaveAgentDialog();
return;
}
if (leaveUserSelectRole.value === 'agent') {
payload.form.agentUid = option.uid;
payload.form.agentEmployeeId = option.employeeId;
payload.form.agentName = option.name;
} else {
payload.form.applicantUid = option.uid;
payload.form.employeeId = option.employeeId;
payload.form.applicantName = option.name;
}
closeLeaveAgentDialog();
saveLocalMessageToBackend(messages.value[sourceIndex]);
};
const browserPanelStyle = computed(() => {
if (viewportWidth.value < 1024) return undefined;
return { width: `${browserPanelWidth.value}px` };
});
const scrollChatToBottom = async () => {
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
container.scrollTo({
top: container.scrollHeight,
behavior: 'auto',
});
};
const scheduleScrollChatToBottom = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
}
scrollToBottomFrame = window.requestAnimationFrame(() => {
scrollToBottomFrame = null;
void scrollChatToBottom();
});
};
const normalizeBrowserInput = (value: string) => {
const raw = (value || '').trim();
if (!raw) return '';
@@ -820,12 +1036,13 @@ const handleSend = async (textOrEvent?: string | Event) => {
};
const validateLeaveForm = (form: LeaveRequestFormData) => {
if (!form.applicantName.trim()) return '申请人不能为空。';
if (!form.applicantName.trim()) return '请假人不能为空。';
if (!form.employeeId.trim()) return '工号不能为空。';
if (!form.leaveType.trim()) return '请选择假别。';
if (!parseDateTime(form.startTime)) return '开始时间格式不正确。';
if (!parseDateTime(form.endTime)) return '结束时间格式不正确。';
if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '结束时间必须晚于开始时间。';
if (!form.agentUid.trim()) return '请选择代理人。';
if (!parseDateTime(form.startTime)) return '请选择正确的开始时间。';
if (!parseDateTime(form.endTime)) return '请选择正确的结束时间。';
if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '时长必须大于0小时,请检查开始时间和结束时间。';
return '';
};
@@ -846,9 +1063,9 @@ const submitLeaveForm = (msg: any) => {
payload.confirmationGenerated = true;
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
messages.value.push({
role: 'assistant',
type: 'leave-confirmation',
const confirmMsg = {
role: 'assistant' as const,
type: 'leave-confirmation' as const,
content: '请确认以下请假信息,确认无误后再提交到 OA。',
payload: {
formId: payload.formId,
@@ -857,7 +1074,12 @@ const submitLeaveForm = (msg: any) => {
},
local_id: newLocalMessageId('leave-confirm'),
local_only: true,
});
};
messages.value.push(confirmMsg);
// 保存更新后的表单消息和新的确认消息
saveLocalMessageToBackend(msg);
saveLocalMessageToBackend(confirmMsg);
};
const editLeaveConfirmation = (msg: any, index: number) => {
@@ -868,8 +1090,14 @@ const editLeaveConfirmation = (msg: any, index: number) => {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.confirmationGenerated = false;
saveLocalMessageToBackend(messages.value[sourceIndex]);
}
}
// 从后端删除对应的确认消息,或者不删除直接隐藏?
// 暂时在前端移除,后端不需要立刻删除(如果没有删除接口),它在会话记录里可能残留。
// 但是我们之前有 /api/chat/messages/local 吗?如果需要,也可以调一个删除接口。
// 为了简单,我们只在前端切除。
messages.value.splice(index, 1);
};
@@ -887,29 +1115,65 @@ const confirmLeaveSubmission = async (msg: any) => {
}
}
await new Promise((resolve) => window.setTimeout(resolve, 900));
try {
const res = await fetch('/api/user/leave-workflow/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload.form),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.error || 'OA 请假提交失败,请稍后重试。');
}
const referenceNo = `OA-${Date.now().toString().slice(-8)}`;
messages.value.push({
role: 'assistant',
type: 'leave-result',
content: `请假单已生成,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。\n\n当前为前端演示提交流程,真实 OA 对接开发中。`,
payload: {
formId: payload.formId,
success: true,
referenceNo,
submittedAt: formatDateTime(new Date()),
},
local_id: newLocalMessageId('leave-result'),
local_only: true,
});
payload.submitting = false;
payload.confirmed = true;
if (sourceIndex >= 0) {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.submitting = false;
const resultMsg = {
role: 'assistant' as const,
type: 'leave-result' as const,
content: `请假单已提交到 OA,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。`,
payload: {
formId: payload.formId,
success: true,
referenceNo: data.request_id || '-',
submittedAt: data.submitted_at || formatDateTime(new Date()),
requestName: data.request_name || '',
},
local_id: newLocalMessageId('leave-result'),
local_only: true,
};
messages.value.push(resultMsg);
payload.confirmed = true;
payload.submitting = false; // Add this line to immediately clear submitting state on success
saveLocalMessageToBackend(msg);
saveLocalMessageToBackend(resultMsg);
} catch (error: any) {
const errorMessage = error?.message || 'OA 请假提交失败,请稍后重试。';
showMessageDialog('error', errorMessage);
const resultMsg = {
role: 'assistant' as const,
type: 'leave-result' as const,
content: `请假单提交失败:${errorMessage}`,
payload: {
formId: payload.formId,
success: false,
referenceNo: '-',
submittedAt: formatDateTime(new Date()),
errorMessage,
},
local_id: newLocalMessageId('leave-result'),
local_only: true,
};
messages.value.push(resultMsg);
saveLocalMessageToBackend(resultMsg);
} finally {
payload.submitting = false;
if (sourceIndex >= 0) {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.submitting = false;
}
}
}
};
@@ -1026,6 +1290,7 @@ onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile();
await loadAgent();
await loadHistory();
@@ -1036,6 +1301,7 @@ onMounted(async () => {
}
// Use config from config.ts instead of API
showChatRating.value = config.workspace?.showChatRating ?? true;
scheduleScrollChatToBottom();
});
onBeforeUnmount(() => {
@@ -1043,8 +1309,26 @@ onBeforeUnmount(() => {
document.removeEventListener('touchstart', handleDocumentPointerDown);
window.removeEventListener('resize', syncViewportWidth);
stopBrowserResize();
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
});
watch(
() => ({
messageCount: messages.value.length,
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
isThinking: isThinking.value,
conversationId: conversationId.value || '',
}),
() => {
scheduleScrollChatToBottom();
},
{ deep: false },
);
/**
* 反馈相关状态
* showChatRating:是否启用评分功能(后续可接入配置)
@@ -1217,9 +1501,13 @@ const showChatRating = ref(false);
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<main
ref="chatScrollContainer"
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'space-y-2 overflow-y-auto scrollbar-thin md:space-y-6'"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
>
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
@@ -1230,14 +1518,9 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
class="group mx-auto flex max-w-4xl gap-4 animate-slide-up mb-6"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>
<!-- AI Avatar -->
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/20">
<Sparkles class="h-4 w-4" />
</div>
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
@@ -1256,7 +1539,7 @@ const showChatRating = ref(false);
<div v-if="msg.type === 'leave-form'" class="space-y-4">
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">
<template v-if="msg.content.includes('或登录OA系统直接申请')">
已为你生成请假申请表,请直接在下方填写并提交。或 <a href="#" @click.prevent="openOALoginModal" class="text-brand-600 font-bold hover:underline">登录OA系统直接申请</a>
已为你生成请假申请表,请直接在下方填写并提交。或 <a href="#" @click.prevent="openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">登录OA系统直接申请</a>
</template>
<template v-else>
{{ msg.content }}
@@ -1264,9 +1547,9 @@ const showChatRating = ref(false);
</div>
<div v-if="getLeaveFormPayload(msg)" class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">申请人</span>
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">填单人</span>
<input
v-model="getLeaveFormPayload(msg)!.form.applicantName"
v-model="getLeaveFormPayload(msg)!.form.fillerName"
type="text"
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
disabled
@@ -1282,7 +1565,7 @@ const showChatRating = ref(false);
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">申请时间</span>
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">创建时间</span>
<input
:value="getLeaveFormPayload(msg)!.form.applyTime.replace('T', ' ')"
type="text"
@@ -1301,6 +1584,52 @@ const showChatRating = ref(false);
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">请假人</span>
<div class="relative">
<input
:value="getLeaveFormPayload(msg)!.form.applicantName ? `${getLeaveFormPayload(msg)!.form.applicantName} / ${getLeaveFormPayload(msg)!.form.employeeId}` : ''"
type="text"
placeholder="请选择请假人"
readonly
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg, 'applicant')"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg, 'applicant')"
title="选择请假人"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">代理人</span>
<div class="relative">
<input
:value="getLeaveAgentDisplayValue(getLeaveFormPayload(msg)!.form)"
type="text"
placeholder="请选择代理人"
readonly
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg)"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg)"
title="选择代理人"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">开始时间</span>
<input
@@ -1337,8 +1666,8 @@ const showChatRating = ref(false);
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
>
<option :value="false">否</option>
<option :value="true">是</option>
<option :value="1">否</option>
<option :value="0">是</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
@@ -1348,8 +1677,8 @@ const showChatRating = ref(false);
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
>
<option :value="false">否</option>
<option :value="true">是</option>
<option :value="1">否</option>
<option :value="0">是</option>
</select>
</label>
</div>
@@ -1370,14 +1699,16 @@ const showChatRating = ref(false);
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">{{ msg.content }}</div>
<div class="rounded-2xl border border-slate-200 bg-slate-50/90 p-4 dark:border-slate-700 dark:bg-slate-800/60">
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-slate-500 dark:text-slate-400">申请人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
<div><span class="text-slate-500 dark:text-slate-400">申请时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
<div><span class="text-slate-500 dark:text-slate-400">填单人:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerName || '暂无数据' }}</div>
<div><span class="text-slate-500 dark:text-slate-400">创建时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
<div><span class="text-slate-500 dark:text-slate-400">请假人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
<div><span class="text-slate-500 dark:text-slate-400">代理人:</span>{{ getLeaveAgentDisplayValue(getLeaveConfirmationPayload(msg)!.form) || '未选择' }}</div>
<div><span class="text-slate-500 dark:text-slate-400">假别:</span>{{ getLeaveTypeLabel(getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
<div><span class="text-slate-500 dark:text-slate-400">时长:</span>{{ formatDurationLabel(getLeaveConfirmationPayload(msg)!.form.durationHours) }}</div>
<div><span class="text-slate-500 dark:text-slate-400">开始时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.startTime.replace('T', ' ') }}</div>
<div><span class="text-slate-500 dark:text-slate-400">结束时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.endTime.replace('T', ' ') }}</div>
<div><span class="text-slate-500 dark:text-slate-400">是否外出:</span>{{ getLeaveConfirmationPayload(msg)!.form.isOutOfOffice ? '是' : '否' }}</div>
<div><span class="text-slate-500 dark:text-slate-400">是否为工伤:</span>{{ getLeaveConfirmationPayload(msg)!.form.isWorkInjury ? '是' : '否' }}</div>
<div><span class="text-slate-500 dark:text-slate-400">是否外出:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isOutOfOffice) }}</div>
<div><span class="text-slate-500 dark:text-slate-400">是否为工伤:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isWorkInjury) }}</div>
</div>
</div>
<div class="flex justify-end gap-3">
@@ -1413,6 +1744,7 @@ const showChatRating = ref(false);
<div
v-else
class="chat-markdown prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 dark:prose-code:bg-slate-800 dark:prose-code:text-blue-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
@click="handleChatMarkdownClick"
v-html="renderMarkdown(msg.content)"
></div>
</div>
@@ -1527,18 +1859,10 @@ const showChatRating = ref(false);
</div>
</div>
<!-- User Avatar -->
<div v-if="msg.role === 'user'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-600 text-white shadow-sm shadow-brand-500/20">
<User class="h-4 w-4" />
</div>
</div>
</template>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl gap-4">
<div class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 shadow-md shadow-brand-500/25">
<Bot class="h-5 w-5 text-white" />
</div>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start">
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-5 py-3 shadow-md dark:border-slate-700 dark:bg-slate-900/85">
<div class="flex gap-1">
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400"></span>
@@ -1548,7 +1872,8 @@ const showChatRating = ref(false);
<span class="text-sm font-medium text-slate-500 dark:text-slate-300">{{ $t('chat.thinking') }}</span>
</div>
</div>
<div v-if="messages.length > 0" class="h-6 md:h-8"></div>
<div v-if="messages.length > 0" class="h-2 md:h-3"></div>
</div>
</main>
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
@@ -1736,48 +2061,84 @@ const showChatRating = ref(false);
showGeneralFeedbackDialog = false;
}"
/>
<div
v-if="showOALoginModal"
v-if="showLeaveAgentDialog"
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
@click.self="closeLeaveAgentDialog"
>
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-900">
<div class="mb-5 flex items-center justify-between">
<h3 class="text-lg font-bold text-slate-800 dark:text-slate-100">登录OA系统</h3>
<button @click="showOALoginModal = false" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
<div class="flex w-full max-w-2xl max-h-[80vh] flex-col rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-900">
<div class="mb-4 flex items-center justify-between">
<div>
<h3 class="text-lg font-bold text-slate-800 dark:text-slate-100">选择{{ leaveUserSelectRole === 'agent' ? '代理人' : '请假人' }}</h3>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">已接入 OA 数据库视图查询。</p>
</div>
<button @click="closeLeaveAgentDialog" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
<X class="h-5 w-5" />
</button>
</div>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="text-sm font-semibold text-slate-600 dark:text-slate-300">账号</label>
<input
v-model="oaLoginForm.username"
type="text"
placeholder="请输入账号"
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-100"
/>
</div>
<div class="space-y-1.5">
<label class="text-sm font-semibold text-slate-600 dark:text-slate-300">密码</label>
<input
v-model="oaLoginForm.password"
type="password"
placeholder="请输入密码"
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-100"
/>
</div>
<button
@click="submitOALogin"
class="mt-2 w-full rounded-xl bg-brand-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-brand-500"
>
确认登录
<div class="mb-4 relative shrink-0">
<input
v-model="leaveAgentKeyword"
@keydown.enter="handleAgentSearch"
type="text"
placeholder="输入姓名或工号搜索,按回车键查询"
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 pr-10 text-sm outline-none transition focus:border-brand-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
/>
<button @click="handleAgentSearch" class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-slate-400 hover:text-brand-600">
<Search class="h-4 w-4" />
</button>
</div>
<div class="flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
<div v-if="leaveAgentLoading && leaveAgentPage === 1" class="flex justify-center py-8">
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
</div>
<div v-else-if="leaveAgentOptions.length === 0" class="py-8 text-center text-sm text-slate-400">
暂无数据
</div>
<template v-else>
<button
v-for="option in leaveAgentOptions"
:key="option.uid"
type="button"
class="flex w-full items-center justify-between rounded-2xl border border-slate-200 px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50 dark:border-slate-700 dark:hover:border-brand-500/40 dark:hover:bg-brand-500/10"
@click="selectLeaveAgent(option)"
>
<div class="space-y-1">
<div class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ option.name }}</div>
<div class="text-xs text-slate-500 dark:text-slate-400">UID:{{ option.uid }}</div>
</div>
<div class="text-right text-xs text-slate-500 dark:text-slate-400">
<div>工号:{{ option.employeeId }}</div>
<div>姓名:{{ option.name }}</div>
</div>
</button>
<div v-if="leaveAgentHasMore" class="flex items-center justify-center space-x-6 py-4">
<button
@click="loadAllAgents"
:disabled="leaveAgentLoading"
class="text-xs text-slate-500 hover:text-slate-700 disabled:opacity-50 dark:text-slate-400 dark:hover:text-slate-300"
>
加载全部
</button>
<button
@click="loadMoreAgents"
:disabled="leaveAgentLoading"
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
>
{{ leaveAgentLoading ? '加载中...' : '加载更多' }}
</button>
</div>
<div v-else class="py-4 text-center text-xs text-slate-400">没有更多数据了</div>
</template>
</div>
</div>
</div>
</template>
</template>
<style scoped>
:deep(.chat-markdown details) {
margin-top: 1rem;
@@ -1812,4 +2173,50 @@ const showChatRating = ref(false);
:deep(.chat-markdown details pre) {
margin-bottom: 0;
}
:deep(.chat-markdown .leave-action-trigger) {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0 0.2rem;
padding: 0.1rem 0.6rem;
border-radius: 9999px;
border: 1px solid rgb(59 130 246 / 0.28);
background: rgb(239 246 255);
color: rgb(29 78 216);
font-weight: 600;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
:deep(.chat-markdown .leave-action-trigger:hover) {
background: rgb(219 234 254);
border-color: rgb(59 130 246 / 0.4);
}
:deep(.chat-markdown .leave-intent-highlight) {
display: inline-block;
margin: 0 0.2rem;
padding: 0.05rem 0.4rem;
border-radius: 0.5rem;
background: rgb(254 249 195);
color: rgb(161 98 7);
font-weight: 600;
}
:deep(.dark .chat-markdown .leave-action-trigger) {
border-color: rgb(96 165 250 / 0.35);
background: rgb(30 41 59);
color: rgb(147 197 253);
}
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
background: rgb(30 64 175 / 0.25);
}
:deep(.dark .chat-markdown .leave-intent-highlight) {
background: rgb(113 63 18 / 0.45);
color: rgb(253 224 71);
}
</style>
+360
View File
@@ -0,0 +1,360 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft, FolderPlus, Pencil, Play, RefreshCw, Settings, Trash2, Wrench, X } from 'lucide-vue-next';
import DifyHealthDialog from '../components/kb/DifyHealthDialog.vue';
import DifySettingsDialog from '../components/kb/DifySettingsDialog.vue';
import {
createKbGroup,
deleteKbGroup,
getKbGroupsSafe,
getKbJobsSafe,
runKbJob,
updateKbGroup,
type KbGroup,
type KbJob,
} from '../api/kb';
const router = useRouter();
const groups = ref<KbGroup[]>([]);
const jobs = ref<KbJob[]>([]);
const isSubmitting = ref(false);
const isRefreshing = ref(false);
const editingGroupId = ref<number | null>(null);
const form = ref({
name: '',
description: '',
});
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const runningJobId = ref<number | string | null>(null);
const settingsDialogOpen = ref(false);
const healthDialogOpen = ref(false);
const formTitle = computed(() => editingGroupId.value ? '编辑知识库分组' : '新建知识库分组');
const formDescription = computed(() => editingGroupId.value
? '修改知识库分组名称和描述,保存后会立即刷新列表。'
: '用于验证主平台里的知识库管理入口和基础接口壳。');
const submitText = computed(() => {
if (isSubmitting.value) return editingGroupId.value ? '保存中...' : '提交中...';
return editingGroupId.value ? '保存修改' : '创建分组';
});
const loadData = async () => {
isRefreshing.value = true;
const [groupsResult, jobsResult] = await Promise.all([getKbGroupsSafe(), getKbJobsSafe()]);
if (groupsResult.ok) {
groups.value = groupsResult.data;
} else {
feedback.value = groupsResult.error || '加载知识库分组失败';
feedbackType.value = 'error';
}
if (jobsResult.ok) {
jobs.value = jobsResult.data;
} else {
feedback.value = jobsResult.error || '加载任务列表失败';
feedbackType.value = 'error';
}
isRefreshing.value = false;
};
const resetForm = () => {
editingGroupId.value = null;
form.value = { name: '', description: '' };
};
const handleCreateGroup = async () => {
if (!form.value.name.trim()) {
feedback.value = '请输入知识库分组名称';
feedbackType.value = 'error';
return;
}
isSubmitting.value = true;
const payload = {
name: form.value.name.trim(),
description: form.value.description.trim(),
};
const result = editingGroupId.value
? await updateKbGroup(editingGroupId.value, payload)
: await createKbGroup(payload);
isSubmitting.value = false;
if (!result.ok) {
feedback.value = result.error || '创建失败';
feedbackType.value = 'error';
return;
}
feedback.value = editingGroupId.value ? '知识库分组已更新' : '知识库分组创建成功';
feedbackType.value = 'success';
resetForm();
await loadData();
};
const handleEditGroup = (group: KbGroup) => {
editingGroupId.value = group.id;
form.value = {
name: group.name,
description: group.description || '',
};
feedback.value = '';
feedbackType.value = '';
};
const handleDeleteGroup = async (group: KbGroup) => {
const confirmed = window.confirm(`确认删除知识库分组「${group.name}」吗?`);
if (!confirmed) return;
const result = await deleteKbGroup(group.id);
if (!result.ok) {
feedback.value = result.error || '删除失败';
feedbackType.value = 'error';
return;
}
if (editingGroupId.value === group.id) {
resetForm();
}
feedback.value = '知识库分组已删除';
feedbackType.value = 'success';
await loadData();
};
const handleRunJob = async (job: KbJob) => {
runningJobId.value = job.id;
const result = await runKbJob(job.id);
runningJobId.value = null;
if (!result.ok) {
feedback.value = result.error || '任务执行失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.run_result || '任务已执行';
feedbackType.value = 'success';
await loadData();
};
onMounted(async () => {
await loadData();
});
</script>
<template>
<div class="min-h-screen bg-gray-50 dark:bg-slate-950 text-slate-800 dark:text-slate-200">
<div class="mx-auto max-w-7xl px-4 py-6 md:px-6 lg:px-8">
<div class="mb-6 flex flex-col gap-4 rounded-3xl border border-slate-200 bg-white p-6 shadow-sm md:flex-row md:items-center md:justify-between dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-4">
<button
@click="router.push('/admin')"
class="rounded-2xl border border-slate-200 p-3 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"
title="返回管理后台"
>
<ArrowLeft class="h-5 w-5" />
</button>
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
<Settings class="h-6 w-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">知识库管理台</h1>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
第一阶段先承接分组、任务和 Dify 管理入口,后续再接入清洗链路。
</p>
</div>
</div>
</div>
<div class="flex items-center gap-3">
<button
@click="loadData"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<RefreshCw class="h-4 w-4" />
刷新数据
</button>
<button
@click="settingsDialogOpen = true"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<Settings class="h-4 w-4" />
Dify 设置
</button>
<button
@click="healthDialogOpen = true"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<RefreshCw class="h-4 w-4" />
健康检查
</button>
<button
@click="router.push('/kb/workspace')"
class="inline-flex items-center gap-2 rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Wrench class="h-4 w-4" />
前往工作台
</button>
</div>
</div>
<div class="grid grid-cols-1 gap-6 xl:grid-cols-[420px_minmax(0,1fr)]">
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-5 flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
<FolderPlus class="h-5 w-5" />
</div>
<div>
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">{{ formTitle }}</h2>
<p class="text-sm text-slate-500 dark:text-slate-400">{{ formDescription }}</p>
</div>
</div>
<div class="space-y-4">
<div>
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组名称</label>
<input v-model="form.name" class="input-field" placeholder="例如:财务制度库" />
</div>
<div>
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组描述</label>
<textarea
v-model="form.description"
rows="4"
class="input-field"
placeholder="描述该知识库分组的业务范围或清洗目标"
/>
</div>
<button
@click="handleCreateGroup"
:disabled="isSubmitting"
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl bg-brand-600 px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
<FolderPlus class="h-4 w-4" />
{{ submitText }}
</button>
<button
v-if="editingGroupId"
@click="resetForm"
type="button"
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<X class="h-4 w-4" />
取消编辑
</button>
<p
v-if="feedback"
class="text-sm"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600 dark:text-emerald-400'"
>
{{ feedback }}
</p>
</div>
</section>
<div class="space-y-6">
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">知识库分组概览</h2>
<span class="text-xs text-slate-400">{{ isRefreshing ? '加载中...' : '`/api/kb/groups`' }}</span>
</div>
<div v-if="groups.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
当前暂无分组,或知识库接口尚未联调完成。
</div>
<div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div
v-for="group in groups"
:key="group.id"
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ group.name }}</div>
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ group.description || '暂无描述' }}</div>
</div>
<div class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{{ group.document_count ?? 0 }} 文档
</div>
</div>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
<div class="text-xs text-slate-400">
更新时间:{{ group.updated_at || '--' }}
</div>
<div class="flex items-center gap-2">
<button
@click="handleEditGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-slate-200 px-3 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
>
<Pencil class="h-3.5 w-3.5" />
编辑
</button>
<button
@click="handleDeleteGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 dark:border-rose-500/30 dark:text-rose-400 dark:hover:bg-rose-500/10"
>
<Trash2 class="h-3.5 w-3.5" />
删除
</button>
</div>
</div>
</div>
</div>
</section>
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">任务队列占位</h2>
<span class="text-xs text-slate-400">`/api/kb/jobs`</span>
</div>
<div v-if="jobs.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
暂无任务。第二阶段会在这里接入清洗、同步和重试任务。
</div>
<div v-else class="space-y-3">
<div
v-for="job in jobs"
:key="job.id"
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ job.job_type }}</div>
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ job.created_at || '--' }}</div>
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
{{ job.message || '暂无任务说明' }}
</div>
<div class="mt-2 text-xs text-slate-400">
文档:{{ job.document_id ?? '--' }} · 版本:{{ job.document_version_id ?? '--' }} · 进度:{{ job.progress ?? 0 }}%
</div>
</div>
<span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{{ job.status }}
</span>
</div>
<div class="mt-3 flex justify-end" v-if="['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'">
<button
@click="handleRunJob(job)"
:disabled="runningJobId === job.id"
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-500/30 dark:text-brand-300 dark:hover:bg-brand-500/10"
>
<Play class="h-3.5 w-3.5" />
{{ runningJobId === job.id ? '执行中...' : '执行任务' }}
</button>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<DifySettingsDialog
:open="settingsDialogOpen"
@close="settingsDialogOpen = false"
@saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
<DifyHealthDialog
:open="healthDialogOpen"
@close="healthDialogOpen = false"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
</template>
File diff suppressed because it is too large. Load diff
+6 -2
View File
@@ -24,7 +24,7 @@ import {
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference } = useTheme();
const { setThemePreference, appliedTheme } = useTheme();
interface ProfileForm {
id: number;
@@ -108,7 +108,11 @@ const fetchProfile = async () => {
const data = await res.json();
user.value = { ...user.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) setThemePreference(data.theme_preference);
if (data.theme_preference) {
setThemePreference(data.theme_preference);
} else {
user.value.theme_preference = appliedTheme.value;
}
captureOriginalProfile();
isEditing.value = false;
} else {
+26 -3
View File
@@ -33,6 +33,7 @@ import {
Edit,
ExternalLink,
Bot,
FileText,
Lock,
User,
Mail,
@@ -48,10 +49,12 @@ import {
ChevronUp
} from 'lucide-vue-next';
import KbWorkspaceView from './KbWorkspaceView.vue';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference } = useTheme();
const { setThemePreference, appliedTheme } = useTheme();
const loadLanguagePreference = () => {
const storedLang = localStorage.getItem('hxops_lang');
@@ -755,7 +758,7 @@ const handleRegister = async () => {
}
};
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates'>('applications');
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base'>('applications');
const isProfileLoading = ref(false);
const isProfileSaving = ref(false);
const isProfileEditing = ref(false);
@@ -840,7 +843,11 @@ const fetchProfile = async () => {
const data = await res.json();
profileUser.value = { ...profileUser.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) setThemePreference(data.theme_preference);
if (data.theme_preference) {
setThemePreference(data.theme_preference);
} else {
profileUser.value.theme_preference = appliedTheme.value;
}
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
@@ -971,6 +978,10 @@ const navigateToApplications = () => openWorkspaceSection('favorites', 'applicat
const navigateToUpdates = () => openWorkspaceSection('announcements', 'updates');
const navigateToKnowledgeBase = () => {
activeSidebarItem.value = 'knowledge_base';
};
const navigateToGeneralChat = () => {
router.push(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
@@ -1378,6 +1389,14 @@ onMounted(async () => {
<LayoutGrid class="h-4 w-4" />
<span>应用管理</span>
</button>
<button
@click="navigateToKnowledgeBase"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
:class="activeSidebarItem === 'knowledge_base' ? 'bg-brand-50 text-brand-700 shadow-sm' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'"
>
<FileText class="h-4 w-4" />
<span>知识库管理</span>
</button>
<button
@click="openGeneralFeedback"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
@@ -1593,6 +1612,10 @@ onMounted(async () => {
</div>
</template>
<template v-else-if="activeSidebarItem === 'knowledge_base'">
<KbWorkspaceView :embedded="true" />
</template>
<template v-else>
<div v-if="wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ wecomEntryHint }}